테스트 환경으로 jsdom(jest-environment-jsdom 패키지 내) 및 node(jest-environment-node 패키지 내)만 지원됩니다. jest-electron-runner의 @jest-runner/electron/environment와 같은 사용자 지정 환경은 지원되지 않습니다.
Mocha 및 Jasmine 프레임워크 어댑터에서 dd-trace>=6.10.0부터 지원됩니다.
dd-trace v6에는 Node.js 22 이상이 필요합니다.
테스트 프레임워크
버전
</md_ta참고 사항
Jest
>= 24.8.0
테스트 환경으로 jsdom(jest-environment-jsdom 패키지 내) 및 node(jest-environment-node 패키지 내)만 지원됩니다. jest-electron-runner의 @jest-runner/electron/environment와 같은 사용자 지정 환경은 지원되지 않습니다.
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.
it('sum function can sum',()=>{consttestSpan=require('dd-trace').scope().active()testSpan.setTag('team_owner','my_team')// test continues normally
// ...
})
이러한 태그에 대한 필터 또는 group by 필드를 생성하려면 먼저 패싯을 생성해야 합니다. 태그 추가에 대한 자세한 내용은 Node.js 사용자 지정 계측 설명서의 태그 추가 섹션을 참조하세요.
테스트에 사용자 지정 측정값 추가
태그와 같이 현재 활성 스팬을 사용하여 테스트에 사용자 지정 측정값을 추가할 수 있습니다.
it('sum function can sum',()=>{consttestSpan=require('dd-trace').scope().active()testSpan.setTag('memory_allocations',16)// test continues normally
// ...
})
Mocha >=9.0.0은 ESM 우선 접근 방식을 사용하여 테스트 파일을 로드합니다. 테스트에 대한 완전한 가시성을 확보하려면 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을 사용하여 테스트 세션의 이름을 지정합니다.
테스트 중인 브라우저 애플리케이션이 브라우저 모니터링을 사용하여 계측되는 경우, Playwright 테스트 결과와 생성된 RUM 브라우저 세션 및 세션 리플레이가 자동으로 연결됩니다. 자세한 내용은 RUM 가이드를 사용하여 브라우저 테스트 계측을 참조하세요.
테스트 실패 스크린샷 업로드
활성화되면 Test Optimization은 테스트가 실패할 때 Playwright가 캡처하는 스크린샷을 업로드합니다. Test Optimization 테스트 세부 정보 사이드 패널의 Media 탭에서 스크린샷을 조회하세요. 이를 실패 시점의 브라우저 상태를 검사하는 데 사용할 수 있습니다.
When('the function is called',function(){conststepSpan=require('dd-trace').scope().active()testSpan.setTag('team_owner','my_team')// test continues normally
// ...
})
이러한 태그에 대한 필터 또는 group by 필드를 생성하려면 먼저 패싯을 생성해야 합니다. 태그 추가에 대한 자세한 내용은 Node.js 사용자 지정 계측 설명서의 태그 추가 섹션을 참조하세요.
테스트에 사용자 지정 측정값 추가
현재 활성 스팬을 가져와 테스트에 사용자 지정 측정값을 추가할 수도 있습니다.
When('the function is called',function(){conststepSpan=require('dd-trace').scope().active()testSpan.setTag('memory_allocations',16)// test continues normally
// ...
})
// 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
returnrequire('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
returnrequire('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
returnrequire('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 브라우저 세션 및 세션 리플레이가 자동으로 연결됩니다. 자세한 내용은 RUM 가이드를 사용하여 브라우저 테스트 계측을 참조하세요.
테스트 실패 스크린샷 업로드
활성화되면 Test Optimization은 테스트가 실패할 때 Cypress가 캡처하는 스크린샷을 업로드합니다. 이 스크린샷은 Test Optimization 테스트 세부 정보 사이드 패널의 Media 탭에 나타납니다. 이를 실패 시점의 브라우저 상태를 검사하는 데 사용할 수 있습니다.
importtracerfrom'dd-trace'import{expect,test}from'vitest'test('sum function can sum',()=>{consttestSpan=tracer.scope().active()testSpan.setTag('team_owner','my_team')expect(1+2).toBe(3)})
이러한 태그에 대한 필터 또는 group by 필드를 생성하려면 먼저 패싯을 생성해야 합니다. 태그 추가에 대한 자세한 내용은 Node.js 사용자 지정 계측 설명서의 태그 추가 섹션을 참조하세요.
현재 활성 스팬을 사용하여 테스트에 사용자 지정 측정값을 추가할 수도 있습니다.
importtracerfrom'dd-trace'import{expect,test}from'vitest'test('sum function can sum',()=>{consttestSpan=tracer.scope().active()testSpan.setTag('memory_allocations',16)expect(1+2).toBe(3)})
참고: 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"}}
테스트에 사용자 지정 태그 또는 측정값 추가
현재 활성 스팬을 사용하여 테스트에 사용자 지정 태그를 추가할 수 있습니다.
importtracerfrom'dd-trace'describe('home page',()=>{it('displays the heading',async()=>{consttestSpan=tracer.scope().active()testSpan.setTag('team_owner','my_team')awaitbrowser.url('/')awaitexpect($('h1')).toBeDisplayed()})})
이러한 태그에 대한 필터 또는 group by 필드를 생성하려면 먼저 패싯을 생성해야 합니다. 태그 추가에 대한 자세한 내용은 Node.js 사용자 지정 계측 설명서의 태그 추가 섹션을 참조하세요.
현재 활성 스팬을 사용하여 테스트에 사용자 지정 측정값을 추가할 수도 있습니다.
importtracerfrom'dd-trace'describe('home page',()=>{it('displays the heading',async()=>{consttestSpan=tracer.scope().active()testSpan.setTag('memory_allocations',16)awaitbrowser.url('/')awaitexpect($('h1')).toBeDisplayed()})})
integration-tests, unit-tests 또는 smoke-tests 등 테스트 그룹을 식별하는 데 사용하세요. 환경 변수: DD_TEST_SESSION_NAME 기본값: dd-trace v6의 경우 jest, mocha, playwright test 또는 cucumber-js와 같은 프레임워크 호출입니다. dd-trace v5의 경우 CI 작업 이름과 테스트 명령의 조합입니다. 예시: unit-tests, integration-tests, smoke-tests
service
테스트 중인 서비스 또는 라이브러리의 이름입니다. 환경 변수: DD_SERVICE 기본값: (테스트 프레임워크 이름) 예시: my-ui
env
테스트가 실행되는 환경의 이름입니다. 환경 변수: DD_ENV 기본값: none 예시: local, ci
url
http://hostname:port 형식의 트레이스 수집용 Datadog Agent URL입니다. 환경 변수: DD_TRACE_AGENT_URL 기본값: http://localhost:8126
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')consttestStartCh=channel('dd-trace:ci:manual:test:start')consttestFinishCh=channel('dd-trace:ci:manual:test:finish')consttestSuite=__filenamedescribe('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')consttestStartCh=channel('dd-trace:ci:manual:test:start')// ... code for your testing framework goes here
beforeEach(()=>{consttestDefinition={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 ...
게시할 페이로드에는 곧 시작될 테스트를 식별하는 문자열인 testName 및 testSuite 속성이 있습니다.
테스트 완료 채널
테스트가 종료됨을 게시하려면 ID dd-trace:ci:manual:test:finish로 이 채널을 가져오세요. 이 작업을 수행하기 좋은 위치는 afterEach 후크 또는 이와 유사한 위치입니다.
const{channel}=require('node:diagnostics_channel')consttestFinishCh=channel('dd-trace:ci:manual:test:finish')// ... code for your testing framework goes here
afterEach(()=>{consttestStatusPayload={status:'fail',error: newError('assertion error')}testStartCh.publish(testStatusPayload)})// code for your testing framework continues here ...
게시할 페이로드에는 status 및 error 속성이 있습니다.
status는 다음 세 가지 값 중 하나를 사용하는 문자열입니다.
테스트 통과 시 * 'pass'
테스트 실패 시 * 'fail'
테스트를 건너뛰면 * 'skip'
error 는 테스트가 실패한 이유를 포함하는 Error 객체입니다.
태그 채널 추가
테스트에 사용자 지정 태그가 필요함을 게시하려면 ID dd-trace:ci:manual:test:addTags로 이 채널을 가져오세요. 이 작업은 테스트 함수 내에서 수행할 수 있습니다.
const{channel}=require('node:diagnostics_channel')consttestAddTagsCh=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})constresult=sum(2,1)assert.equal(result,3)})// code for your testing framework continues here ...
게시할 페이로드는 테스트에 추가되는 태그 또는 측정값의 딕셔너리 <string, string|number>입니다.
테스트 실행
테스트 시작 및 종료 채널이 코드에 있으면 다음 환경 변수를 포함하여 평소와 같이 테스팅 프레임워크를 실행합니다.
브라우저 테스트는 mocha, jest, cucumber, cypress, playwright로 실행되고 vitest는 dd-trace-js로 계측되지만 브라우저 세션 자체에 대한 가시성은 기본적으로 제공되지 않습니다(예: 네트워크 호출, 사용자 액션, 페이지 로드 등).
Cypress 대화형 모드(cypress open을 실행하여 진입 가능)는 before:run과 같은 일부 Cypress 이벤트가 발생하지 않기 때문에 Test Optimization에서 지원되지 않습니다. 그래도 시도하려면 experimentalInteractiveRunEvents: true를 Cypress 구성 파일에 전달하세요.
Cypress 테스트 격리가 필요한 재시도
Cypress 테스트 격리가 활성화되어 있어야(기본값)
재시도 기반 Test Optimization 기능이 작동합니다. testIsolation이 Cypress 구성에서
false로 설정된 경우, dd-trace가
조기 불안정성 탐지, 자동 테스트 재시도 및
해결 시도 등 모든 테스트 재시도를 비활성화합니다. 이러한 기능은 각 테스트를 제자리에서 다시 실행하는데 이를 위해서는 격리가 필요하기 때문입니다.
격리가 비활성화되면 트레이서가 경고 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 우선 접근 방식을 사용하며 계측을 위해 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의 경우 다음과 같습니다.