| title | JavaScript and TypeScript Tests | ||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| code_lang | javascript | ||||||||||||||||||||||||||||
| type | multi-code-lang | ||||||||||||||||||||||||||||
| code_lang_weight | 20 | ||||||||||||||||||||||||||||
| aliases |
|
||||||||||||||||||||||||||||
| further_reading |
|
{{< tabs >}} {{% tab "dd-trace v6" %}}
| Test Framework | Version | Notes |
|---|---|---|
| Jest | >= 28.0.0 | Only jsdom (in the jest-environment-jsdom package) and node (in the jest-environment-node package) are supported as test environments. Custom environments like @jest-runner/electron/environment in jest-electron-runner are not supported.Only jest-circus is supported as testRunner.test.concurrent is supported from dd-trace>=6.1.0. |
| Mocha | >= 8.0.0 | |
| Cucumber | >= 7.0.0 | |
| Cypress | >= 12.0.0 | |
| Playwright | >= 1.38.0 | |
| Vitest | >= 1.6.0 | test.concurrent is supported from dd-trace>=6.1.0. |
dd-trace v6 requires Node.js 22 or later.
{{% /tab %}} {{% tab "dd-trace v5" %}}
| Test Framework | Version | Notes |
|---|---|---|
| Jest | >= 24.8.0 | Only jsdom (in the jest-environment-jsdom package) and node (in the jest-environment-node package) are supported as test environments. Custom environments like @jest-runner/electron/environment in jest-electron-runner are not supported.Only jest-circus is supported as testRunner.test.concurrent is supported from dd-trace>=5.112.0. |
| Mocha | >= 5.2.0 | |
| Cucumber | >= 7.0.0 | |
| Cypress | >= 6.7.0 | |
| Playwright | >= 1.18.0 | |
| Vitest | >= 1.6.0 | Supported from dd-trace>=5.18.0. test.concurrent is supported from dd-trace>=5.112.0. |
{{% /tab %}} {{< /tabs >}}
The instrumentation works at runtime, so any transpilers such as TypeScript, Webpack, or Babel are supported out-of-the-box.
To report test results to Datadog, you need to configure the Datadog JavaScript library:
{{< tabs >}} {{% tab "CI Provider with Auto-Instrumentation Support" %}} {{% ci-autoinstrumentation %}}
{{% /tab %}}
{{% tab "Other Cloud CI Provider" %}} {{% ci-agentless %}}
{{% /tab %}} {{% tab "On-Premises CI Provider" %}} {{% ci-agent %}} {{% /tab %}} {{< /tabs >}}
To install the JavaScript Tracer, run:
yarn add --dev dd-traceFor more information, see the JavaScript Tracer installation documentation.
{{< tabs >}}
{{% tab "Jest/Mocha" %}}
Set the NODE_OPTIONS environment variable to -r dd-trace/ci/init. Run your tests as you normally would, optionally specifying a name for your test session with DD_TEST_SESSION_NAME:
NODE_OPTIONS="-r dd-trace/ci/init" DD_TEST_SESSION_NAME=unit-tests yarn testNote: If you set a value for NODE_OPTIONS, make sure it does not overwrite -r dd-trace/ci/init. This can be done using the ${NODE_OPTIONS:-} clause:
{{< code-block lang="json" filename="package.json" >}} { "scripts": { "test": "NODE_OPTIONS="--max-old-space-size=12288 ${NODE_OPTIONS:-}" jest" } } {{< /code-block >}}
You can add custom tags to your tests by using the current active span:
it('sum function can sum', () => {
const testSpan = require('dd-trace').scope().active()
testSpan.setTag('team_owner', 'my_team')
// test continues normally
// ...
})To create filters or group by fields for these tags, you must first create facets. For more information about adding tags, see the Adding Tags section of the Node.js custom instrumentation documentation.
Just like tags, you can add custom measures to your tests by using the current active span:
it('sum function can sum', () => {
const testSpan = require('dd-trace').scope().active()
testSpan.setTag('memory_allocations', 16)
// test continues normally
// ...
})For more information about custom measures, see the Add Custom Measures Guide.
Mocha >=9.0.0 uses an ESM-first approach to load test files. Set NODE_OPTIONS to -r dd-trace/ci/init --import dd-trace/register.js to get full visibility into your tests. See dd-trace-js ESM support for more information.
{{% /tab %}}
{{% tab "Playwright" %}}
Set the NODE_OPTIONS environment variable to -r dd-trace/ci/init. Run your tests as you normally would, optionally specifying a name for your test session with DD_TEST_SESSION_NAME:
NODE_OPTIONS="-r dd-trace/ci/init" DD_TEST_SESSION_NAME=e2e-tests yarn test:e2eNote: If you set a value for NODE_OPTIONS, make sure it does not overwrite -r dd-trace/ci/init. This can be done using the ${NODE_OPTIONS:-} clause:
{{< code-block lang="json" filename="package.json" >}} { "scripts": { "test": "NODE_OPTIONS="--max-old-space-size=12288 ${NODE_OPTIONS:-}" jest" } } {{< /code-block >}}
You can add custom tags to your tests by using the current active span:
test('user profile', async ({ page }) => {
const testSpan = require('dd-trace').scope().active()
testSpan.setTag('team_owner', 'my_team')
// ...
})
test('landing page', async ({ page }) => {
const testSpan = require('dd-trace').scope().active()
testSpan.setTag('test.cpu.usage', 'high')
// ...
})To create filters or group by fields for these tags, you must first create facets. For more information about adding tags, see the Adding Tags section of the Node.js custom instrumentation documentation.
You can also add custom measures to your tests by using the current active span:
test('user profile', async ({ page }) => {
const testSpan = require('dd-trace').scope().active()
testSpan.setTag('memory_allocations', 16)
// ...
})For more information about custom measures, see the Add Custom Measures Guide.
If the browser application being tested is instrumented using Browser Monitoring, the Playwright test results and their generated RUM browser sessions and session replays are automatically linked. For more information, see the Instrumenting your browser tests with RUM guide.
When enabled, Test Optimization uploads screenshots that Playwright captures when a test fails. View the screenshots in the {{< ui >}}Media{{< /ui >}} tab of the Test Optimization test details side panel. Use them to inspect browser state at the time of failure.
{{< img src="continuous_integration/tests/setup/playwright-failure-screenshot-media-tab.png" alt="A Playwright failure screenshot displayed in the Media tab of the Test Optimization test details side panel." style="width:100%;" >}}
Use dd-trace v5.116.0 or later on the v5 release line, or dd-trace v6.5.0 or later on the v6 release line.
To enable screenshot uploads, set the DD_TEST_FAILURE_SCREENSHOTS_ENABLED environment variable to 1. In your Playwright configuration, set screenshot under use to one of the following values:
'on': Capture screenshot after each test.'only-on-failure': Capture screenshot after each test failure.'on-first-failure': Capture screenshot after each test's first failure.
Note: If you use 'on', Test Optimization only uploads screenshots from failed tests.
{{% /tab %}}
{{% tab "Cucumber" %}}
Set the NODE_OPTIONS environment variable to -r dd-trace/ci/init. Run your tests as you normally would, optionally specifying a name for your test session with DD_TEST_SESSION_NAME:
NODE_OPTIONS="-r dd-trace/ci/init" DD_TEST_SESSION_NAME=integration-tests yarn test:integrationNote: If you set a value for NODE_OPTIONS, make sure it does not overwrite -r dd-trace/ci/init. This can be done using the ${NODE_OPTIONS:-} clause:
{{< code-block lang="json" filename="package.json" >}} { "scripts": { "test": "NODE_OPTIONS="--max-old-space-size=12288 ${NODE_OPTIONS:-}" jest" } } {{< /code-block >}}
You can add custom tags to your test by grabbing the current active span:
When('the function is called', function () {
const stepSpan = require('dd-trace').scope().active()
testSpan.setTag('team_owner', 'my_team')
// test continues normally
// ...
})To create filters or group by fields for these tags, you must first create facets. For more information about adding tags, see the Adding Tags section of the Node.js custom instrumentation documentation.
You may also add custom measures to your test by grabbing the current active span:
When('the function is called', function () {
const stepSpan = require('dd-trace').scope().active()
testSpan.setTag('memory_allocations', 16)
// test continues normally
// ...
})For more information about custom measures, see the Add Custom Measures Guide.
{{% /tab %}}
{{% tab "Cypress" %}}
Use the Cypress API documentation to learn how to use plugins for cypress>=10.
In your cypress.config.js file, set the following:
{{< code-block lang="javascript" filename="cypress.config.js" >}} const { defineConfig } = require('cypress')
module.exports = defineConfig({ e2e: { setupNodeEvents: require('dd-trace/ci/cypress/plugin'), supportFile: 'cypress/support/e2e.js' } }) {{< /code-block >}}
Add the following line to the top level of your supportFile:
{{< code-block lang="javascript" filename="cypress/support/e2e.js" >}} // Your code can be before this line // require('./commands') require('dd-trace/ci/cypress/support') // Also supported: // import 'dd-trace/ci/cypress/support' // Your code can also be after this line // Cypress.Commands.add('login', (email, pw) => {}) {{< /code-block >}}
If you're using other Cypress plugins, your cypress.config.js file should contain the following:
{{< code-block lang="javascript" filename="cypress.config.js" >}} const { defineConfig } = require('cypress')
module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { // your previous code is before this line return require('dd-trace/ci/cypress/plugin')(on, config) } } }) {{< /code-block >}}
Datadog requires the after:run Cypress event to work, and Cypress does not allow multiple handlers for that event. If you defined handlers for after:run already, add the Datadog handler manually by importing 'dd-trace/ci/cypress/after-run':
{{< code-block lang="javascript" filename="cypress.config.js" >}} const { defineConfig } = require('cypress')
module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { require('dd-trace/ci/cypress/plugin')(on, config) // other plugins on('after:run', (details) => { // other 'after:run' handlers // important that this function call is returned return require('dd-trace/ci/cypress/after-run')(details) }) } } }) {{< /code-block >}}
Datadog requires the after:spec Cypress event to work, and Cypress does not allow multiple handlers for that event. If you defined handlers for after:spec already, add the Datadog handler manually by importing 'dd-trace/ci/cypress/after-spec':
{{< code-block lang="javascript" filename="cypress.config.js" >}} const { defineConfig } = require('cypress')
module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { require('dd-trace/ci/cypress/plugin')(on, config) // other plugins on('after:spec', (...args) => { // other 'after:spec' handlers // Important that this function call is returned // Important that all the arguments are passed return require('dd-trace/ci/cypress/after-spec')(...args) }) } } }) {{< /code-block >}}
Run your tests as you normally would, optionally specifying a name for your test session with DD_TEST_SESSION_NAME:
{{< code-block lang="shell" >}} DD_TEST_SESSION_NAME=ui-tests yarn test:ui {{< /code-block >}}
To add additional information to your tests, such as the team owner, use cy.task('dd:addTags', { yourTags: 'here' }) in your test or hooks.
For example:
beforeEach(() => {
cy.task('dd:addTags', {
'before.each': 'certain.information'
})
})
it('renders a hello world', () => {
cy.task('dd:addTags', {
'team.owner': 'ui'
})
cy.get('.hello-world')
.should('have.text', 'Hello World')
})To create filters or group by fields for these tags, you must first create facets. For more information about adding tags, see the Adding Tags section of the Node.js custom instrumentation documentation.
To add custom measures to your tests, such as memory allocations, use cy.task('dd:addTags', { yourNumericalTags: 1 }) in your test or hooks.
For example:
it('renders a hello world', () => {
cy.task('dd:addTags', {
'memory_allocations': 16
})
cy.get('.hello-world')
.should('have.text', 'Hello World')
})For more information about custom measures, see the Add Custom Measures Guide.
If the browser application being tested is instrumented using Browser Monitoring, the Cypress test results and their generated RUM browser sessions and session replays are automatically linked. For more information, see the Instrumenting your browser tests with RUM guide.
When enabled, Test Optimization uploads screenshots that Cypress captures when a test fails. They appear in the {{< ui >}}Media{{< /ui >}} tab of the Test Optimization test details side panel. Use them to inspect browser state at the time of failure.
{{< img src="continuous_integration/tests/setup/cypress-failure-screenshot-media-tab.png" alt="A Cypress failure screenshot displayed in the Media tab of the Test Optimization test details side panel." style="width:100%;" >}}
Use dd-trace v5.112.0 or later on the v5 release line, or dd-trace v6.1.0 or later on the v6 release line.
To enable screenshot uploads, set the DD_TEST_FAILURE_SCREENSHOTS_ENABLED environment variable to 1. In your Cypress configuration, make sure screenshotOnRunFailure is set to true (the default).
{{% /tab %}}
{{% tab "Vitest" %}}
Use a Node.js version supported by your dd-trace major version for Vitest instrumentation:
dd-tracev5 requires Node.js 18.19+ or Node.js 20.6+.dd-tracev6 requires Node.js 22 or later.
Set the NODE_OPTIONS environment variable to --import dd-trace/register.js -r dd-trace/ci/init. Run your tests as you normally would, optionally specifying a name for your test session with DD_TEST_SESSION_NAME:
NODE_OPTIONS="--import dd-trace/register.js -r dd-trace/ci/init" DD_TEST_SESSION_NAME=smoke-tests yarn test:smokeNote: If you set a value for NODE_OPTIONS, make sure it does not overwrite --import dd-trace/register.js -r dd-trace/ci/init. This can be done using the ${NODE_OPTIONS:-} clause:
{{< code-block lang="json" filename="package.json" >}} { "scripts": { "test": "NODE_OPTIONS="--max-old-space-size=12288 ${NODE_OPTIONS:-}" vitest run" } } {{< /code-block >}}
You can add custom tags to your tests by using the current active span:
import tracer from 'dd-trace'
import { expect, test } from 'vitest'
test('sum function can sum', () => {
const testSpan = tracer.scope().active()
testSpan.setTag('team_owner', 'my_team')
expect(1 + 2).toBe(3)
})To create filters or group by fields for these tags, you must first create facets. For more information about adding tags, see the Adding Tags section of the Node.js custom instrumentation documentation.
You can also add custom measures to your tests by using the current active span:
import tracer from 'dd-trace'
import { expect, test } from 'vitest'
test('sum function can sum', () => {
const testSpan = tracer.scope().active()
testSpan.setTag('memory_allocations', 16)
expect(1 + 2).toBe(3)
})For more information about custom measures, see the Add Custom Measures Guide.
{{% /tab %}}
{{< /tabs >}}
When using dd-trace, you might encounter the following error message:
Error: Cannot find module 'dd-trace/ci/init'
This might be because of an incorrect usage of NODE_OPTIONS.
For example, if your GitHub Action looks like this:
jobs:
my-job:
name: Run tests
runs-on: ubuntu-latest
# Invalid NODE_OPTIONS
env:
NODE_OPTIONS: -r dd-trace/ci/init
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node
uses: actions/setup-node@v3
- name: Install dependencies
run: npm install
- name: Run tests
run: npm testNote: This does not work because NODE_OPTIONS are interpreted by every node process, including npm install. If you try to import dd-trace/ci/init before it's installed, this step fails.
Your GitHub Action should instead look like this:
jobs:
my-job:
name: Run tests
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Install node
uses: actions/setup-node@v3
- name: Install dependencies
run: npm install
- name: Run tests
run: npm test
env:
NODE_OPTIONS: -r dd-trace/ci/initFollow these best practices:
- Make sure the
NODE_OPTIONSenvironment variable is only set to the process running tests. - Specifically avoid defining
NODE_OPTIONSin the global environment variables settings in your pipeline or job definition.
If you're using yarn>=2 and a .pnp.cjs file, you might also get the same error:
Error: Cannot find module 'dd-trace/ci/init'
You can fix it by setting NODE_OPTIONS to the following:
NODE_OPTIONS="-r $(pwd)/.pnp.cjs -r dd-trace/ci/init" yarn testWhen tests are instrumented with Istanbul, the Datadog Tracer (v3.20.0 or later) reports it under the test.code_coverage.lines_pct tag for your test sessions.
You can see the evolution of the test coverage in the Coverage tab of a test session.
For more information, see Code Coverage.
The following is a list of the most important configuration settings that can be used with the SDK.
test_session.name
: Use it to identify a group of tests, such as integration-tests, unit-tests or smoke-tests.
Environment variable: DD_TEST_SESSION_NAME
Default: For dd-trace v6, the framework invocation, such as jest, mocha, playwright test, or cucumber-js. For dd-trace v5, a combination of CI job name and test command.
Example: unit-tests, integration-tests, smoke-tests
service
: Name of the service or library under test.
Environment variable: DD_SERVICE
Default: (test framework name)
Example: my-ui
env
: Name of the environment where tests are being run.
Environment variable: DD_ENV
Default: none
Examples: local, ci
url
: Datadog Agent URL for trace collection in the form http://hostname:port.
Environment variable: DD_TRACE_AGENT_URL
Default: http://localhost:8126
For more information about service and env reserved tags, see Unified Service Tagging. All other Datadog Tracer configuration options can also be used.
{{% ci-git-metadata %}}
dd-trace versions 5.23.0 and 4.47.0.
If you use Jest, Mocha, Cypress, Playwright, Cucumber, or Vitest, do not use the manual testing API, as Test Optimization automatically instruments them and sends the test results to Datadog. The manual testing API is incompatible with already supported testing frameworks.
Use the manual testing API only if you use an unsupported testing framework or have a different testing mechanism.
The manual testing API leverages the node:diagnostics_channel module from Node.js and is based on channels you can publish to:
const { channel } = require('node:diagnostics_channel')
const { describe, test, beforeEach, afterEach, assert } = require('my-custom-test-framework')
const testStartCh = channel('dd-trace:ci:manual:test:start')
const testFinishCh = channel('dd-trace:ci:manual:test:finish')
const testSuite = __filename
describe('can run tests', () => {
beforeEach((testName) => {
testStartCh.publish({ testName, testSuite })
})
afterEach((status, error) => {
testFinishCh.publish({ status, error })
})
test('first test will pass', () => {
assert.equal(1, 1)
})
})Grab this channel by its ID dd-trace:ci:manual:test:start to publish that a test is starting. A good place to do this is a beforeEach hook or similar.
const { channel } = require('node:diagnostics_channel')
const testStartCh = channel('dd-trace:ci:manual:test:start')
// ... code for your testing framework goes here
beforeEach(() => {
const testDefinition = {
testName: 'a-string-that-identifies-this-test',
testSuite: 'what-suite-this-test-is-from.js'
}
testStartCh.publish(testDefinition)
})
// code for your testing framework continues here ...The payload to be published has attributes testName and testSuite, both strings, that identify the test that is about to start.
Grab this channel by its ID dd-trace:ci:manual:test:finish to publish that a test is ending. A good place to do this is an afterEach hook or similar.
const { channel } = require('node:diagnostics_channel')
const testFinishCh = channel('dd-trace:ci:manual:test:finish')
// ... code for your testing framework goes here
afterEach(() => {
const testStatusPayload = {
status: 'fail',
error: new Error('assertion error')
}
testStartCh.publish(testStatusPayload)
})
// code for your testing framework continues here ...The payload to be published has attributes status and error:
-
statusis a string that takes one of three values:'pass'when a test passes.'fail'when a test fails.'skip'when a test has been skipped.
-
erroris anErrorobject containing the reason why a test failed.
Grab this channel by its ID dd-trace:ci:manual:test:addTags to publish that a test needs custom tags. This can be done within the test function:
const { channel } = require('node:diagnostics_channel')
const testAddTagsCh = channel('dd-trace:ci:manual:test:addTags')
// ... code for your testing framework goes here
test('can sum', () => {
testAddTagsCh.publish({ 'test.owner': 'my-team', 'number.assertions': 3 })
const result = sum(2, 1)
assert.equal(result, 3)
})
// code for your testing framework continues here ...The payload to be published is a dictionary <string, string|number> of tags or measures that are added to the test.
When the test start and end channels are in your code, run your testing framework like you normally do, including the following environment variables:
NODE_OPTIONS="-r dd-trace/ci/init" DD_TEST_SESSION_NAME=custom-tests yarn run-my-test-frameworkBrowser tests executed with mocha, jest, cucumber, cypress, playwright, and vitest are instrumented by dd-trace-js, but visibility into the browser session itself is not provided by default (for example, network calls, user actions, page loads, and more.).
If you want visibility into the browser process, consider using RUM & Session Replay. When using Cypress or Playwright, test results and their generated RUM browser sessions and session replays are automatically linked. For more information, see the Instrumenting your browser tests with RUM guide.
Cypress interactive mode (which you can enter by running cypress open) is not supported by Test Optimization because some cypress events, such as before:run, are not fired. If you want to try it anyway, pass experimentalInteractiveRunEvents: true to the cypress configuration file.
Jest's --forceExit option may cause data loss. Datadog tries to send data immediately after your tests finish, but shutting down the process abruptly can cause some requests to fail. Use --forceExit with caution.
Mocha's --exit option may cause data loss. Datadog tries to send data immediately after your tests finish, but shutting down the process abruptly can cause some requests to fail. Use --exit with caution.
Vitest's browser mode is not supported.
By default, Vitest's isolate option is true, so each test file runs in its own fork or thread. Vitest is ESM-first and relies on import-in-the-middle for instrumentation, which incurs a setup cost every time a suite starts. With isolation, that setup cost is repeated for every file. The effect is largest when you have many small, fast suites, because setup time can dominate wall-clock time.
To lower overhead, set isolate: false in your Vitest config file, or pass --no-isolate to the test command.
To keep Vitest isolation enabled with lower worker startup overhead, set DD_EXPERIMENTAL_TEST_OPT_VITEST_NO_WORKER_INIT=true. This option is available in dd-trace v5 (from 5.111.0) and v6 (from 6.0.0). It applies to isolated Vitest worker-pool runs with Vitest 3.2.6 and later, and falls back to normal worker instrumentation for unsupported configurations.
Because this mode does not initialize dd-trace in Vitest workers, the following features are not supported:
- Custom test tags
- Custom spans
- Log correlation from test code
- Failed Test Replay
Follow these practices to take full advantage of the testing framework and Test Optimization.
Whenever possible, leverage the tools that testing frameworks provide for parameterized tests. For example, for jest:
Avoid this: {{< code-block lang="javascript" >}} [[1,2,3], [3,4,7]].forEach((a,b,expected) => { test('sums correctly', () => { expect(a+b).toEqual(expected) }) }) {{< /code-block >}}
And use test.each instead:
{{< code-block lang="javascript" >}} test.each([[1,2,3], [3,4,7]])('sums correctly %i and %i', (a,b,expected) => { expect(a+b).toEqual(expected) }) {{< /code-block >}}
For mocha, use mocha-each:
{{< code-block lang="javascript" >}} const forEach = require('mocha-each'); forEach([ [1,2,3], [3,4,7] ]) .it('adds %i and %i then returns %i', (a,b,expected) => { expect(a+b).to.equal(expected) }); {{< /code-block >}}
When you use this approach, both the testing framework and Test Optimization can tell your tests apart.
Use DD_TEST_SESSION_NAME to define the name of the test session and the related group of tests. Examples of values for this tag would be:
unit-testsintegration-testssmoke-testsflaky-testsui-testsbackend-tests
If DD_TEST_SESSION_NAME is not specified, the default value is:
- For
dd-tracev6, the framework invocation, such asjest,mocha,playwright test, orcucumber-js - For
dd-tracev5, a combination of the CI job name and the command used to run the tests (for example,my-ci-job yarn test)
The test session name should be unique within a repository to help you distinguish different groups of tests.
{{< partial name="whats-next/whats-next.html" >}}