JavaScript Unit Testing
Relevant source files
The following files were used as context for generating this wiki page:
The project utilizes JavaScript unit tests to ensure the correctness and reliability of its Node.js-based scripts, particularly those involved in the documentation build process. The primary goal is to validate the logic of individual modules in isolation.
The testing strategy is built upon the Jest framework, which provides a comprehensive testing environment including a test runner, assertion library, and mocking capabilities. Tests are configured to run in a simulated browser environment using jsdom. The setup also includes integration with Datadog's Test Optimization features, allowing for the collection and analysis of test results, performance metrics, and code coverage.
Testing Framework and Environment
The project relies on Jest as its primary JavaScript testing framework. The necessary dependencies are defined in package.json.
Sources: package.json:34-35, package.json:65-72, jest.config.js
Key Dependencies
| Dependency | Version | Description |
|---|---|---|
jest | ^29.7.0 | The core testing framework. |
jest-environment-jsdom | ^29.7.0 | Provides a simulated DOM environment for tests, allowing for the testing of scripts that might interact with browser-like objects. |
babel-jest | ^29.7.0 | A Jest transformer that uses Babel to transpile JavaScript files before they are run, enabling the use of modern JavaScript syntax. |
@babel/core | ^7.23.3 | The core Babel compiler. |
@babel/preset-env | ^7.23.3 | A Babel preset that allows using the latest JavaScript features by transpiling them to a compatible version. |
Sources: package.json:34-35, 43-45
Test Execution
Tests are executed using a yarn script defined in package.json.
yarn run jest-test
This command invokes the Jest test runner, which then discovers and executes all test files matching the configured patterns.
Sources: package.json:12, CLAUDE.md:18
The following diagram illustrates the test execution flow.
This diagram shows the process from running the test command to Jest executing the tests based on the project's configuration.
Sources: package.json:12, jest.config.js:2-3
Test Configuration
Jest's behavior is configured in the jest.config.js file at the root of the project. This file dictates how tests are discovered, transformed, and executed.
Sources: jest.config.js
jest.config.js Breakdown
| Option | Value | Description |
|---|---|---|
testEnvironment | 'jsdom' | Specifies that tests should be run in a simulated DOM environment. |
testMatch | ['**/tests/**/*.test.js'] | A glob pattern that tells Jest where to find test files. It looks for any .test.js file within any tests directory. |
moduleNameMapper | See below | An object that maps module paths to different paths, similar to aliases. This helps resolve module imports within the tests. |
transform | {'^.+\\.js$': 'babel-jest'} | Specifies that all .js files should be processed by babel-jest. This enables the use of modern JavaScript syntax in test files. |
Sources: jest.config.js:2-10
moduleNameMapper
This configuration is crucial for resolving module imports correctly within the test environment. It prevents issues with relative paths and allows for cleaner import statements.
// jest.config.js
module.exports = {
// ... other options
moduleNameMapper: {
'assets/scripts/(.*)': '<rootDir>/assets/scripts/$1'
},
// ... other options
};
Sources: jest.config.js:5-7
Test Structure and Example
Tests are structured using Jest's describe and it blocks. The describe block groups related tests for a specific module or function, while the it block defines an individual test case.
Sources: assets/scripts/tests/build-api-pages.test.js
Example: build-api-pages.test.js
This test file validates the functionality of the build-api-pages.js script. A key feature demonstrated is the use of jest.mock() to isolate the script from external dependencies like the file system (fs) and glob.
// assets/scripts/tests/build-api-pages.test.js
jest.mock('fs');
jest.mock('glob');
const fs = require('fs');
const glob = require('glob');
const { getEndpoints } = require('../build-api-pages.js');
describe('build-api-pages', () => {
describe('getEndpoints', () => {
it('should return a list of endpoints', () => {
// ... test implementation
});
});
});
Sources: assets/scripts/tests/build-api-pages.test.js:1-10
The following sequence diagram shows how dependencies are mocked and how the getEndpoints function is tested.
This diagram illustrates the interaction between the test, the function under test (getEndpoints), and its mocked dependencies (glob and fs).
Sources: assets/scripts/tests/build-api-pages.test.js
Test Optimization Integration
The project is configured to report test results to Datadog for visibility and optimization. This is achieved by using the dd-trace library.
Sources: content/en/tests/setup/javascript.md
Setup and Instrumentation
-
Installation: The
dd-tracepackage is added as a development dependency.yarn add --dev dd-trace -
Instrumentation: Tests are instrumented by pre-loading the
dd-trace/ci/initmodule using theNODE_OPTIONSenvironment variable when running the test command.NODE_OPTIONS="-r dd-trace/ci/init" yarn test
Configuration
The integration is configured using environment variables.
| Environment Variable | Description - |
| DD_TEST_SESSION_NAME | Identifies a group of tests, such as unit-tests or integration-tests. - |
| DD_SERVICE | Name of the service or library under test. Defaults to the test framework name. - |
| DD_ENV | Name of the environment where tests are being run (e.g., local, ci). - |
| DD_TRACE_AGENT_URL | The URL for the Datadog Agent (e.g., http://hostname:port). Defaults to http://localhost:8126. - |
Sources: content/en/tests/setup/javascript.md:148-171
Adding Custom Tags and Measures
The dd-trace library allows for adding custom tags and measures to test spans, providing richer context in the Datadog UI. This is done by accessing the active span within a test.
// Example from content/en/tests/setup/javascript.md
it('sum function can sum', () => {
const testSpan = require('dd-trace').scope().active()
testSpan.setTag('team_owner', 'my_team') // Custom Tag
testSpan.setTag('memory_allocations', 16) // Custom Measure
// test continues normally
// ...
})
Sources: content/en/tests/setup/javascript.md:73-81, content/en/tests/setup/javascript.md:89-97
Summary
The JavaScript unit testing setup in this repository provides a robust foundation for verifying the functionality of build scripts. It uses Jest for its powerful testing and mocking capabilities and is fully integrated with Datadog's Test Optimization platform via dd-trace. This integration enables comprehensive monitoring, analysis, and optimization of the test suite, contributing to the overall quality and stability of the documentation build process.