This product is not supported for your selected Datadog site. ().

互換性

テストフレームワークバージョンメモ
Jest>= 28.0.0jsdom (jest-environment-jsdom パッケージ内) および node (jest-environment-node パッケージ内) のみテスト環境としてサポートされています。jest-electron-runner@jest-runner/electron/environment にあるようなカスタム環境はサポートされていません。

jest-circus のみ testRunner としてサポートされています。

test.concurrentdd-trace>=6.1.0 からサポートされています。
Mocha>= 8.0.0
Cucumber>= 7.0.0
Cypress>= 12.0.0
Playwright>= 1.38.0
Vitest>= 1.6.0test.concurrentdd-trace>=6.1.0 からサポートされています。ブラウザモードdd-trace>=6.8.0 からサポートされています。
WebdriverIO>= 9.0.0Mocha および Jasmine フレームワークアダプターで dd-trace>=6.10.0 からサポートされています。

dd-trace v6 には Node.js 22 以降が必要です。

テストフレームワークバージョンメモ
Jest>= 24.8.0jsdom (jest-environment-jsdom パッケージ内) おおよび node (jest-environment-node パッケージ内) のみテスト環境としてサポートされています。jest-electron-runner@jest-runner/electron/environment にあるようなカスタム環境はサポートされていません。

jest-circus のみ testRunner としてサポートされています。

test.concurrentdd-trace>=5.112.0 からサポートされています。
Mocha>= 5.2.0
Cucumber>= 7.0.0
Cypress>= 6.7.0
Playwright>= 1.18.0
Vitest>= 1.6.0dd-trace>=5.18.0 からサポートされています。test.concurrentdd-trace>=5.112.0 からサポートされています。ブラウザモードdd-trace>=5.119.0 からサポートされています。
WebdriverIO>= 9.0.0Mocha および Jasmine フレームワークアダプターで dd-trace>=5.121.0 からサポートされています。

インスツルメンテーションは実行時に動作するため、TypeScript、Webpack、Babel などのトランスパイラーにすぐに対応できます。

報告方法の構成

Datadog にテスト結果を報告するには、Datadog JavaScript ライブラリを構成する必要があります。

We support auto-instrumentation for the following CI providers:

CI ProviderAuto-Instrumentation method
GitHub ActionsDatadog Test Visibility Github Action
JenkinsUI-based configuration with Datadog Jenkins plugin
GitLabDatadog Test Visibility GitLab Script
CircleCIDatadog Test Visibility CircleCI Orb

Auto-instrumentation runs on the CI executor and does not automatically apply to tests in a separate container. Before using it for containerized tests, see Tests in Containers.

If the auto-instrumentation step configures the process that runs your tests, you can skip the rest of the setup steps below.

: 自動インスツルメンテーションは、Cypress テストではサポートされていません。Cypress テストをインスツルメンテーションするには、以下に記載されている手動インスツルメンテーションの手順に従ってください。

If you are using a cloud CI provider without access to the underlying worker nodes, such as GitHub Actions or CircleCI, configure the library to use the Agentless mode. For this, set the following environment variables:

DD_CIVISIBILITY_AGENTLESS_ENABLED=true (Required)
Enables or disables Agentless mode.
Default: false
DD_API_KEY (Required)
The Datadog API key used to upload the test results.
Default: (empty)

Additionally, configure the Datadog site to which you want to send data.

DD_SITE (Required)
The Datadog site to upload results to.
Default: datadoghq.com

If you are running tests on an on-premises CI provider, such as Jenkins or self-managed GitLab CI, install the Datadog Agent on each worker node by following the Agent installation instructions. This is the recommended option as it allows you to automatically link test results to logs and underlying host metrics.

If you are using a Kubernetes executor, Datadog recommends using the Datadog Operator. The operator includes Datadog Admission Controller which can automatically inject the tracer library into the build pods. Note: If you use the Datadog Operator, there is no need to download and inject the tracer library since the Admission Controller can do this for you, so you can skip the corresponding step below. However, you still need to make sure that your pods set the environment variables or command-line parameters necessary to enable Test Visibility.

If you are not using Kubernetes or can’t use the Datadog Admission Controller and the CI provider is using a container-based executor, set the DD_TRACE_AGENT_URL environment variable (which defaults to http://localhost:8126) in the build container running the tracer to an endpoint that is accessible from within that container. Note: Using localhost inside the build references the container itself and not the underlying worker node or any container where the Agent might be running in.

DD_TRACE_AGENT_URL includes the protocol and port (for example, http://localhost:8126) and takes precedence over DD_AGENT_HOST and DD_TRACE_AGENT_PORT, and is the recommended configuration parameter to configure the Datadog Agent’s URL for CI Visibility.

If you still have issues connecting to the Datadog Agent, use the Agentless Mode. Note: When using this method, tests are not correlated with logs and infrastructure metrics.

JavaScript トレーサーのインストール

JavaScript Tracer をインストールするには、次を実行します。

yarn add --dev dd-trace

詳しくは、JavaScript Tracer のインストールに関するドキュメント を参照してください。

テストのインスツルメンテーション

環境変数 NODE_OPTIONS-r dd-trace/ci/init に設定します。通常通りテストを実行します。オプションで DD_TEST_SESSION_NAME を使用してテストセッションの名前を指定することもできます。

NODE_OPTIONS="-r dd-trace/ci/init" DD_TEST_SESSION_NAME=unit-tests yarn test

: NODE_OPTIONS に値を設定する場合は、-r dd-trace/ci/init を上書きしないように注意してください。これは ${NODE_OPTIONS:-} 節を使用して行うことができます。

package.json

{
  "scripts": {
    "test": "NODE_OPTIONS=\"--max-old-space-size=12288 ${NODE_OPTIONS:-}\" jest"
  }
}

テストにカスタムタグを追加する

現在アクティブなスパンを使用して、テストにカスタムタグを追加することができます。

  it('sum function can sum', () => {
    const testSpan = require('dd-trace').scope().active()
    testSpan.setTag('team_owner', 'my_team')
    // test continues normally
    // ...
  })

これらのタグに対してフィルターや group by フィールドを作成するには、まずファセットを作成する必要があります。タグの追加の詳細については、Node.js カスタムインスツルメンテーションドキュメントの タグの追加 セクションを参照してください。

テストへのカスタム測定値の追加

タグと同様に、現在アクティブなスパンを使用して、テストにカスタム測定値を追加できます。

  it('sum function can sum', () => {
    const testSpan = require('dd-trace').scope().active()
    testSpan.setTag('memory_allocations', 16)
    // test continues normally
    // ...
  })

カスタム測定値の詳細については、カスタム測定値の追加ガイド を参照してください。

Mocha ECMAScript モジュール (ESM)

Mocha >=9.0.0 は、テストファイルの読み込みに ESM-first アプローチを採用しています。テストの完全な可視性を得るには、NODE_OPTIONS-r dd-trace/ci/init --import dd-trace/register.js に設定します。詳細については、dd-trace-js ESM サポート を参照してください。

環境変数 NODE_OPTIONS-r dd-trace/ci/init に設定します。通常通りテストを実行します。オプションで DD_TEST_SESSION_NAME を使用してテストセッションの名前を指定することもできます。

NODE_OPTIONS="-r dd-trace/ci/init" DD_TEST_SESSION_NAME=e2e-tests yarn test:e2e

: NODE_OPTIONS に値を設定する場合は、-r dd-trace/ci/init を上書きしないように注意してください。これは ${NODE_OPTIONS:-} 節を使用して行うことができます。

package.json

{
  "scripts": {
    "test": "NODE_OPTIONS=\"--max-old-space-size=12288 ${NODE_OPTIONS:-}\" jest"
  }
}

テストにカスタムタグを追加する

現在アクティブなスパンを使用して、テストにカスタムタグを追加することができます。

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')
  // ...
})

これらのタグに対してフィルターや group by フィールドを作成するには、まずファセットを作成する必要があります。タグの追加の詳細については、Node.js カスタムインスツルメンテーションドキュメントの タグの追加 セクションを参照してください。

テストへのカスタム測定値の追加

現在アクティブなスパンを使用して、テストにカスタム測定値を追加することもできます。

test('user profile', async ({ page }) => {
  const testSpan = require('dd-trace').scope().active()
  testSpan.setTag('memory_allocations', 16)
  // ...
})

カスタム測定値の詳細については、カスタム測定値の追加ガイド を参照してください。

Playwright - RUM インテグレーション

テスト対象のブラウザアプリケーションが Browser Monitoring を使用してインスツルメントされている場合、Playwright テストの結果と生成された RUM ブラウザセッションおよびセッションリプレイは自動的にリンクされます。詳細については、RUM によるブラウザテストのインスツルメントガイド を参照してください。

テストの失敗スクリーンショットをアップロードする

有効にすると、Test Optimization はテストが失敗したときに Playwright がキャプチャしたスクリーンショットをアップロードします。スクリーンショットは、Test Optimization テスト詳細サイドパネルの Media タブで表示します。これらを使用して、失敗時のブラウザの状態を調査します。

Test Optimization テスト詳細サイドパネルのメディアタブに表示された Playwright の失敗スクリーンショット。

v5 リリースラインでは dd-trace v5.116.0 以降 を、v6 リリースラインでは dd-trace v6.5.0 以降 を使用してください。

スクリーンショットのアップロードを有効にするには、DD_TEST_FAILURE_SCREENSHOTS_ENABLED 環境変数を 1 に設定します。Playwright 構成の usescreenshot を以下のいずれかの値に設定します。

  • 'on': 各テストの後にスクリーンショットをキャプチャします。
  • 'only-on-failure': 各テスト失敗の後にスクリーンショットをキャプチャします。
  • 'on-first-failure': 各テストの最初の失敗の後にスクリーンショットをキャプチャします。

: 'on' を使用する場合、Test Optimization は失敗したテストのスクリーンショットのみをアップロードします。

環境変数 NODE_OPTIONS-r dd-trace/ci/init に設定します。通常通りテストを実行します。オプションで DD_TEST_SESSION_NAME を使用してテストセッションの名前を指定することもできます。

NODE_OPTIONS="-r dd-trace/ci/init" DD_TEST_SESSION_NAME=integration-tests yarn test:integration

: NODE_OPTIONS に値を設定する場合は、-r dd-trace/ci/init を上書きしないように注意してください。これは ${NODE_OPTIONS:-} 節を使用して行うことができます。

package.json

{
  "scripts": {
    "test": "NODE_OPTIONS=\"--max-old-space-size=12288 ${NODE_OPTIONS:-}\" jest"
  }
}

テストにカスタムタグを追加する

現在アクティブなスパンをつかんで、テストにカスタムタグを追加することができます。

  When('the function is called', function () {
    const stepSpan = require('dd-trace').scope().active()
    testSpan.setTag('team_owner', 'my_team')
    // test continues normally
    // ...
  })

これらのタグに対してフィルターや group by フィールドを作成するには、まずファセットを作成する必要があります。タグの追加の詳細については、Node.js カスタムインスツルメンテーションドキュメントの タグの追加 セクションを参照してください。

テストへのカスタム測定値の追加

現在アクティブなスパンをつかんで、テストにカスタム測定値を追加することもできます。

  When('the function is called', function () {
    const stepSpan = require('dd-trace').scope().active()
    testSpan.setTag('memory_allocations', 16)
    // test continues normally
    // ...
  })

カスタム測定値の詳細については、カスタム測定値の追加ガイド を参照してください。

Cypress バージョン 10 以降

Cypress API ドキュメントを使用して、cypress>=10 のための プラグインの使用方法を学ぶ ことができます。

cypress.config.js ファイルで、以下を設定します。

cypress.config.js

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents: require('dd-trace/ci/cypress/plugin'),
    supportFile: 'cypress/support/e2e.js'
  }
})

次の行を supportFileトップレベルに追加します。

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) => {})

他の Cypress プラグインを使用している場合、cypress.config.js ファイルに以下の内容が含まれている必要があります。

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)
    }
  }
})

Cypress after:run イベント

Datadog が機能するには after:run Cypress イベントが必要ですが、Cypress はそのイベントに対して複数のハンドラーを許可していません。after:run のハンドラーをすでに定義している場合は、'dd-trace/ci/cypress/after-run' をインポートして Datadog ハンドラーを手動で追加します。

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)
      })
    }
  }
})

Cypress after:spec イベント

Datadog が機能するには after:spec Cypress イベントが必要ですが、Cypress はそのイベントに対して複数のハンドラーを許可していません。after:spec のハンドラーをすでに定義している場合は、'dd-trace/ci/cypress/after-spec' をインポートして Datadog ハンドラーを手動で追加します。

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)
      })
    }
  }
})

通常通りテストを実行します。オプションで DD_TEST_SESSION_NAME を使用してテストセッションの名前を指定することもできます。

DD_TEST_SESSION_NAME=ui-tests yarn test:ui

テストにカスタムタグを追加する

チーム所有者などの追加情報をテストに追加するには、テストまたはフック内で cy.task('dd:addTags', { yourTags: 'here' }) を使用します。

たとえば、以下のとおりです。

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')
})

これらのタグに対してフィルターや group by フィールドを作成するには、まずファセットを作成する必要があります。タグの追加の詳細については、Node.js カスタムインスツルメンテーションドキュメントの タグの追加 セクションを参照してください。

テストへのカスタム測定値の追加

メモリ割り当てなどのカスタム測定値をテストに追加するには、テストまたはフック内で cy.task('dd:addTags', { yourNumericalTags: 1 }) を使用します。

たとえば、以下のとおりです。

it('renders a hello world', () => {
  cy.task('dd:addTags', {
    'memory_allocations': 16
  })
  cy.get('.hello-world')
    .should('have.text', 'Hello World')
})

カスタム測定値の詳細については、カスタム測定値の追加ガイド を参照してください。

Cypress - RUM インテグレーション

テスト対象のブラウザアプリケーションが Browser Monitoring を使用してインスツルメントされている場合、Cypress テストの結果と生成された RUM ブラウザセッションおよびセッションリプレイは自動的にリンクされます。詳細については、RUM によるブラウザテストのインスツルメントガイド を参照してください。

テストの失敗スクリーンショットをアップロードする

有効にすると、Test Optimization はテストが失敗したときに Cypress がキャプチャしたスクリーンショットをアップロードします。これらは Test Optimization テスト詳細サイドパネルの Media タブに表示されます。これらを使用して、失敗時のブラウザの状態を調査します。

Test Optimization テスト詳細サイドパネルのメディアタブに表示された Cypress の失敗スクリーンショット。

v5 リリースラインでは dd-trace v5.112.0 以降 を、v6 リリースラインでは dd-trace v6.1.0 以降 を使用してください。

スクリーンショットのアップロードを有効にするには、DD_TEST_FAILURE_SCREENSHOTS_ENABLED 環境変数を 1 に設定します。Cypress 構成で、screenshotOnRunFailuretrue (デフォルト) に設定されていることを確認してください。

: Vitest は ESM ファーストであるため、その構成は他のテストフレームワークとは異なります。

Vitest インスツルメンテーションには、dd-trace メジャーバージョンでサポートされている Node.js バージョンを使用してください。

  • dd-trace v5 には Node.js 18.19 以降または Node.js 20.6 以降が必要です。
  • dd-tracev6 には Node.js 22 以降が必要です。

環境変数 NODE_OPTIONS--import dd-trace/register.js -r dd-trace/ci/init に設定します。通常通りテストを実行します。オプションで DD_TEST_SESSION_NAME を使用してテストセッションの名前を指定することもできます。

NODE_OPTIONS="--import dd-trace/register.js -r dd-trace/ci/init" DD_TEST_SESSION_NAME=smoke-tests yarn test:smoke

: NODE_OPTIONS に値を設定する場合は、--import dd-trace/register.js -r dd-trace/ci/init を上書きしないように注意してください。これは ${NODE_OPTIONS:-} 節を使用して行うことができます。

package.json

{
  "scripts": {
    "test": "NODE_OPTIONS=\"--max-old-space-size=12288 ${NODE_OPTIONS:-}\" vitest run"
  }
}

テストへのカスタムタグまたは測定値の追加

現在アクティブなスパンを使用して、テストにカスタムタグを追加することができます。

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)
})

これらのタグに対してフィルターや group by フィールドを作成するには、まずファセットを作成する必要があります。タグの追加の詳細については、Node.js カスタムインスツルメンテーションドキュメントの タグの追加 セクションを参照してください。

現在アクティブなスパンを使用して、テストにカスタム測定値を追加することもできます。

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)
})

カスタム測定値の詳細については、カスタム測定値の追加ガイド を参照してください。

WebdriverIO インスツルメンテーションには、dd-trace メジャーバージョンでサポートされている Node.js バージョンを使用してください。

  • dd-trace v5 には Node.js 18.19 以降または Node.js 20.6 以降が必要です。
  • dd-tracev6 には Node.js 22 以降が必要です。

環境変数 NODE_OPTIONS--import dd-trace/register.js -r dd-trace/ci/init に設定します。通常通りテストを実行します。オプションで DD_TEST_SESSION_NAME を使用してテストセッションの名前を指定することもできます。

NODE_OPTIONS="--import dd-trace/register.js -r dd-trace/ci/init" DD_TEST_SESSION_NAME=e2e-tests yarn test:e2e

: NODE_OPTIONS に値を設定する場合は、--import dd-trace/register.js -r dd-trace/ci/init を上書きしないように注意してください。これは ${NODE_OPTIONS:-} 節を使用して行うことができます。

package.json

{
  "scripts": {
    "test:e2e": "NODE_OPTIONS=\"--max-old-space-size=12288 ${NODE_OPTIONS:-}\" wdio run ./wdio.conf.js"
  }
}

テストへのカスタムタグまたは測定値の追加

現在アクティブなスパンを使用して、テストにカスタムタグを追加することができます。

import tracer from 'dd-trace'

describe('home page', () => {
  it('displays the heading', async () => {
    const testSpan = tracer.scope().active()
    testSpan.setTag('team_owner', 'my_team')

    await browser.url('/')
    await expect($('h1')).toBeDisplayed()
  })
})

これらのタグに対してフィルターや group by フィールドを作成するには、まずファセットを作成する必要があります。タグの追加の詳細については、Node.js カスタムインスツルメンテーションドキュメントの タグの追加 セクションを参照してください。

現在アクティブなスパンを使用して、テストにカスタム測定値を追加することもできます。

import tracer from 'dd-trace'

describe('home page', () => {
  it('displays the heading', async () => {
    const testSpan = tracer.scope().active()
    testSpan.setTag('memory_allocations', 16)

    await browser.url('/')
    await expect($('h1')).toBeDisplayed()
  })
})

カスタム測定値の詳細については、カスタム測定値の追加ガイド を参照してください。

「Cannot find module ‘dd-trace/ci/init’」エラーの修正方法

dd-trace を使用している場合、次のエラーメッセージが表示されることがあります。

 Error: Cannot find module 'dd-trace/ci/init'

これは NODE_OPTIONS の誤った使用が原因である可能性があります。

たとえば、GitHub Action が次のようになっている場合です。

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 test

注: NODE_OPTIONSnpm install を含むすべてのノードプロセスによって解釈されるため、これは機能しません。インストールされる前に dd-trace/ci/init をインポートしようとすると、このステップは失敗します。

GitHub Action は代わりに次のようになっている必要があります。

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/init

以下のベストプラクティスに従ってください。

  • テストを実行するプロセスにのみ NODE_OPTIONS 環境変数が設定されていることを確認してください。
  • 特に、パイプラインまたはジョブ定義のグローバル環境変数設定で NODE_OPTIONS を定義することはしないでください。

Yarn 2 以降の使用

yarn>=2.pnp.cjs ファイルを使用している場合、同じエラーが発生する可能性があります。

 Error: Cannot find module 'dd-trace/ci/init'

NODE_OPTIONS を以下のように設定することで修正できます:

NODE_OPTIONS="-r $(pwd)/.pnp.cjs -r dd-trace/ci/init" yarn test

コードカバレッジを報告する

テストに Istanbul がインスツルメンテーションされると、Datadog トレーサー (v3.20.0 以降) はテストセッションの test.code_coverage.lines_pct タグでそれを報告します。

テストセッションの Coverage タブで、テストカバレッジの推移を見ることができます。

詳しくは、Code Coverage を参照してください。

コンフィギュレーション設定

以下は、SDK で使用できる最も重要なコンフィギュレーション設定のリストです。

test_session.name
integration-testsunit-tests、または smoke-tests などのテストグループを識別するために使用します。
環境変数: DD_TEST_SESSION_NAME
デフォルト: dd-trace v6 の場合、jestmochaplaywright test、または cucumber-js などのフレームワーク呼び出し。dd-trace v5 の場合、CI ジョブ名とテストコマンドの組み合わせ。
: unit-testsintegration-testssmoke-tests
service
テスト対象のサービスまたはライブラリの名前。
環境変数: DD_SERVICE
デフォルト: (テストフレームワーク名)
: my-ui
env
テストが実行されている環境の名前。
環境変数: DD_ENV
デフォルト: none
: localci
url
http://hostname:port 形式のトレース収集用の Datadog Agent URL。
環境変数: DD_TRACE_AGENT_URL
デフォルト: http://localhost:8126

service および env の予約タグの詳細については、Unified Service Tagging を参照してください。他のすべての Datadog トレーサーコンフィギュレーション オプションも使用できます。

Git のメタデータを収集する

Datadog uses Git information for visualizing your test results and grouping them by repository, branch, and commit. Git metadata is automatically collected by the test instrumentation from CI provider environment variables and the local .git folder in the project path, if available.

If you are running tests in non-supported CI providers or with no .git folder, you can set the Git information manually using environment variables. These environment variables take precedence over any auto-detected information. Set the following environment variables to provide Git information:

DD_GIT_REPOSITORY_URL
URL of the repository where the code is stored. Both HTTP and SSH URLs are supported.
Example: git@github.com:MyCompany/MyApp.git, https://github.com/MyCompany/MyApp.git
DD_GIT_BRANCH
Git branch being tested. Leave empty if providing tag information instead.
Example: develop
DD_GIT_TAG
Git tag being tested (if applicable). Leave empty if providing branch information instead.
Example: 1.0.1
DD_GIT_COMMIT_SHA
Full commit hash.
Example: a18ebf361cc831f5535e58ec4fae04ffd98d8152
DD_GIT_COMMIT_MESSAGE
Commit message.
Example: Set release number
DD_GIT_COMMIT_AUTHOR_NAME
Commit author name.
Example: John Smith
DD_GIT_COMMIT_AUTHOR_EMAIL
Commit author email.
Example: john@example.com
DD_GIT_COMMIT_AUTHOR_DATE
Commit author date in ISO 8601 format.
Example: 2021-03-12T16:00:28Z
DD_GIT_COMMIT_COMMITTER_NAME
Commit committer name.
Example: Jane Smith
DD_GIT_COMMIT_COMMITTER_EMAIL
Commit committer email.
Example: jane@example.com
DD_GIT_COMMIT_COMMITTER_DATE
Commit committer date in ISO 8601 format.
Example: 2021-03-12T16:00:28Z

手動テスト API

: 手動テスト API は、 dd-trace バージョン 5.23.0 および 4.47.0から利用可能です。

Jest、Mocha、Cypress、Playwright、Cucumber、Vitest、または WebdriverIO を使用している場合は、手動テスト API を使用しないでください。Test Optimization は、これらのフレームワークに対して自動的にインスツルメンテーションを行い、テスト結果を Datadog に送信します。手動テスト API は、サポートされているテストフレームワークと互換性がありません

サポートされていないテストフレームワークを使用している場合や、別のテストメカニズムを持っている場合のみ、手動テスト API を使用してください。

手動テスト API は、Node.js の node:diagnostics_channel モジュールを活用し、以下に公開可能なチャンネルに基づいています。

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)
  })
})

テスト開始チャンネル

このチャンネルを ID dd-trace:ci:manual:test:start で取得して、テストが開始されることを公開します。これを行うのに適した場所は、beforeEach フックなどです。

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 ...

公開されるペイロードには testNametestSuite という属性があり、どちらも文字列です。これは開始しようとしているテストを識別します。

テスト終了チャンネル

このチャンネルを ID dd-trace:ci:manual:test:finish で取得して、テストが終了されることを公開します。これを行うのに適した場所は、afterEach フックなどです。

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 ...

公開されるペイロードには statuserror という属性があります。

  • status は、以下の 3 つの値のうちの 1 つを取る文字列です。 テストがパスしたら * 'pass'。 テストが失敗したら * 'fail'。 テストがスキップされたら * 'skip'

  • errorは、テストが失敗した理由を含む Error オブジェクトです。

タグ追加チャンネル

このチャンネルを ID dd-trace:ci:manual:test:addTags で取得して、テストにカスタムタグが必要であることを公開します。これはテスト関数内で行うことができます。

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 ...

公開されるペイロードは、テストに追加されるタグまたは測定値の辞書 <string, string|number> です。

テストを実行する

テスト開始チャンネルと終了チャンネルをコードに入れたら、以下の環境変数を含めて、いつものようにテストフレームワークを実行します。

NODE_OPTIONS="-r dd-trace/ci/init" DD_TEST_SESSION_NAME=custom-tests yarn run-my-test-framework

既知の制限

ブラウザテスト

mochajestcucumbercypressplaywright、および vitest で実行されるブラウザテストは dd-trace-js によりインスツルメントされますが、ブラウザセッション自体の可視性はデフォルトでは提供されません (ネットワーク呼び出し、ユーザーのアクション、ページロードなど)。

ブラウザ処理の可視性を希望する場合は、RUM & Session Replay の使用を検討してください。Cypress または Playwright を使用していると、テスト結果とそれによって生成された RUM ブラウザセッションおよびセッションリプレイは自動的にリンクされます。詳細については、RUM によるブラウザテストのインスツルメントガイド を参照してください。

Cypress インタラクティブモード

Cypress インタラクティブモード (cypress open を実行して開始可能) は、before:run などの一部の Cypress イベントが発生しないため、Test Optimization ではサポートされていません。それでも試したい場合は、Cypress 構成ファイルexperimentalInteractiveRunEvents: true を渡してください。

再試行には Cypress テスト分離が必要

Cypress の テスト分離 は、 再試行ベースの Test Optimization 機能が動作するために有効 (デフォルト) になっている必要があります。testIsolationfalse に設定されている場合、を Cypress 設定に指定すると、dd-trace はすべてのテストの 再試行 Early Flake DetectionAuto Test Retries、および attempt to fix を無効にします。これらの機能は各テストをその場で再実行するため、分離が必要となるからです。

分離が無効になっている場合、トレーサーは警告 Test isolation is disabled, retries will not be enabled を記録し、テスト実行に @test.test_management.is_attempt_to_fix タグは付けられません。トレーサーはグローバル testIsolation 値を読み取るため、スイートごとの describe オーバーライドでは再試行は再有効化されません。

Jest の --forceExit

Jest の –forceExit オプションはデータ損失を引き起こす可能性があります。Datadog はテスト終了直後にデータを送信しようとしますが、プロセスを突然シャットダウンすると一部のリクエストが失敗する可能性があります。--forceExit は注意して使用してください。

Mocha の --exit

Mocha の –exit オプションはデータ損失を引き起こす可能性があります。Datadog はテスト終了直後にデータを送信しようとしますが、プロセスを突然シャットダウンすると一部のリクエストが失敗する可能性があります。--exit は注意して使用してください。

Vitest のテスト実行時間のオーバーヘッド

デフォルトでは、Vitest の isolate オプションは true であるため、各テストファイルは独自のフォークまたはスレッドで実行されます。Vitest は ESM-first であり、インスツルメンテーションに import-in-the-middle を使用しているため、スイートが開始されるたびにセットアップコストが発生します。分離により、そのセットアップコストがファイルごとに繰り返されます。セットアップタイムがウォールクロックタイムの大部分を占める可能性があるため、この影響は小さくて高速なスイートが多数ある場合に最大となります。

オーバーヘッドを減らすには、Vitest 構成ファイルで isolate: false を設定するか、テストコマンドに --no-isolate を渡してください。

Vitest の分離を有効にしたままワーカー起動のオーバーヘッドを低減するには、DD_EXPERIMENTAL_TEST_OPT_VITEST_NO_WORKER_INIT=true を設定してください。このオプションは dd-trace v5 (5.111.0 以降) および v6 (6.0.0 以降) で使用可能です。これは Vitest 3.2.6 以降の分離された Vitest ワーカープールの実行に適用され、サポートされていない構成では通常のワーカーインスツルメンテーションにフォールバックします。

このモードでは Vitest ワーカー内で dd-trace を初期化しないため、以下の機能はサポートされていません。

  • カスタムテストタグ
  • カスタムスパン
  • テストコードからのログの相関付け
  • 失敗したテストのリプレイ

ベストプラクティス

テストフレームワークと Test Optimization を最大限に活用するために、以下のプラクティスに従ってください。

パラメーター化されたテスト

可能な限り、テストフレームワークが提供するパラメーター化されたテスト用のツールを活用してください。たとえば、jest を利用できます。

以下は避けてください。

[[1,2,3], [3,4,7]].forEach((a,b,expected) => {
  test('sums correctly', () => {
    expect(a+b).toEqual(expected)
  })
})

代わりに test.each を使用してください。

test.each([[1,2,3], [3,4,7]])('sums correctly %i and %i', (a,b,expected) => {
  expect(a+b).toEqual(expected)
})

mocha の場合は、mocha-each を使用してください。

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)
});

この方法を使用すると、テストフレームワークと Test Optimization の両方でテストを区別することができます。

テストセッション名 DD_TEST_SESSION_NAME

DD_TEST_SESSION_NAME を使用してテストセッションの名前と関連するテストグループを定義します。このタグの値の例は次のとおりです。

  • unit-tests
  • integration-tests
  • smoke-tests
  • flaky-tests
  • ui-tests
  • backend-tests

DD_TEST_SESSION_NAME が指定されていない場合、デフォルト値は次のようになります。

  • dd-trace v6 の場合、jestmochaplaywright test、または cucumber-js などのフレームワーク呼び出し
  • dd-trace v5 の場合、CI ジョブ名とテストの実行に使用されるコマンドの組み合わせ (例: my-ci-job yarn test)

テストセッション名は、異なるテストグループを区別しやすくするためにリポジトリ内で一意でなければなりません。

参考資料