Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
4a40d6e
rename forEach file
BenoitZugmeyer Feb 26, 2026
29aeddc
vitest setup
BenoitZugmeyer Jan 21, 2025
c309d19
♻️ adapt vitest setup to current main
thomas-lebeau Oct 13, 2026
e8f30f3
🚨 fix typecheck, lint and karma for the vitest setup
thomas-lebeau Oct 13, 2026
901b51d
👷 declare vitest dependencies in LICENSE-3rdparty.csv
thomas-lebeau Oct 13, 2026
9b6be97
👷 run unit tests with vitest instead of karma
thomas-lebeau Oct 13, 2026
c31ed25
⚡️ run unit test files in a shared page (isolate: false)
thomas-lebeau Oct 14, 2026
4c08724
🐛 pre-bundle react/jsx-dev-runtime so Vite doesn't reload the shared …
thomas-lebeau Oct 14, 2026
3835124
♻️ import noop from @datadog/js-core/util
thomas-lebeau Oct 15, 2026
627a3a8
📝 update the running-tests skill for Vitest unit tests
thomas-lebeau Oct 15, 2026
9945e02
👌 drop the duplicate uncaught error disabling and document the two he…
thomas-lebeau Nov 3, 2026
d3bece0
✅ restore the page URL after each test
thomas-lebeau Nov 3, 2026
4cf72f5
👌 record Jasmine failures before throwing and check console calls aft…
thomas-lebeau Nov 3, 2026
7bcfe94
👌 restore the page URL after the cleanup tasks of the test
thomas-lebeau Nov 4, 2026
1261399
✅ only define prototype toJSON methods synchronously in specs
thomas-lebeau Nov 5, 2026
71391be
👌 run Vitest setup files in order, cover developer-extension, documen…
thomas-lebeau Nov 6, 2026
758dce0
👌 don't collect developer-extension coverage
thomas-lebeau Nov 10, 2026
edd8020
👌 preserve suffix matching in coverage exclusions
thomas-lebeau Nov 11, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .claude/skills/running-tests/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: running-tests
description: Use when running tests or checks in browser-sdk, including unit (Karma/Jasmine), E2E (Playwright), script tests, TypeScript/SSR compatibility, performance benchmarks, or BrowserStack. Use when choosing a yarn test command, reproducing a flaky seed, or targeting a spec, a browser, or a pinned old browser.
description: Use when running tests or checks in browser-sdk, including unit (Vitest Browser Mode, Jasmine API shim), E2E (Playwright), script tests, TypeScript/SSR compatibility, performance benchmarks, or BrowserStack. Use when choosing a yarn test command, reproducing a flaky seed, or targeting a spec, a browser, or a pinned old browser.
---

# Running Tests in browser-sdk
Expand All @@ -13,10 +13,10 @@ All test entry points are root `yarn` scripts. Unit tests compile from source. L

| Need | Command |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
| Unit, watch mode (`localhost:9876`, `/debug.html` for devtools) | `yarn test` |
| Unit, watch mode (`--browser.headless=false` to open the browser and its devtools) | `yarn test` |
| Unit, single run | `yarn test:unit` |
| Specific specs (repeatable, quoted globs OK, also works with `yarn test`) | `yarn test:unit --spec 'packages/browser-rum-core/src/domain/view/**/*.spec.ts'` |
| Reproduce a CI order (`Randomized with seed 41027`) | `yarn test:unit --seed 41027` |
| Specific specs (paths or filename filters, also works with `yarn test`) | `yarn test:unit packages/browser-rum-core/src/domain/view/` |
| Reproduce a CI order (`Running tests with seed "41027"`) | `yarn test:unit --sequence.seed=41027` |
| Unit on BrowserStack (`BS_USERNAME`/`BS_ACCESS_KEY` in env or `.env`) | `yarn test:unit:bs` |
| Script tests (`scripts/**/*.spec.ts`) | `yarn test:script` |
| One script spec (`yarn test:script <file>` still runs all of them) | `node --test --experimental-test-module-mocks scripts/lib/foo.spec.ts` |
Expand Down
13 changes: 7 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ yarn build:apps
# Run unit tests
yarn test:unit

# Run specific test file
yarn test:unit --spec packages/browser-core/src/path/to/feature.spec.ts
# Run specific test files (paths or filename filters)
yarn test:unit packages/browser-core/src/path/to/feature.spec.ts

# Run tests on a specific seed
yarn test:unit --seed 123
# Run tests on a specific seed (printed as "Running tests with seed ...")
yarn test:unit --sequence.seed=123

# setup E2E tests (installs Playwright and builds test apps)
yarn test:e2e:setup
Expand Down Expand Up @@ -78,7 +78,8 @@ test/
├── apps/ # Test apps for E2E and performance testing
├── e2e/ # Playwright E2E test scenarios
├── performance/ # Performance benchmarking tests
└── unit/ # Karma/Jasmine unit test configuration
├── unit/ # Karma configuration for BrowserStack unit tests
└── unit-vitest/ # Vitest unit test configuration (Jasmine compatibility shim)

scripts/ # Build, deploy, release automation
```
Expand All @@ -99,7 +100,7 @@ For deeper context, see:

### Unit Tests

- Test framework: Jasmine + Karma. Spec files co-located with implementation: `feature.ts` → `feature.spec.ts`
- Test framework: Jasmine API on Vitest Browser Mode (via a shim in `test/unit-vitest/`), Karma for BrowserStack. Spec files co-located with implementation: `feature.ts` → `feature.spec.ts`
- Focus tests with `fit()` / `fdescribe()`, skip with `xit()` / `xdescribe()`
- Use `registerCleanupTask()` for cleanup, NOT `afterEach()`
- Prefer `collectAsyncCalls(spy, n)` over `waitFor(() => spy.calls.count() > 0)` for waiting on spy calls
Expand Down
10 changes: 7 additions & 3 deletions LICENSE-3rdparty.csv
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ dev,@angular/core,MIT,Copyright (c) 2010-2024 Google LLC
dev,@angular/platform-browser,MIT,Copyright (c) 2010-2024 Google LLC
dev,@angular/router,MIT,Copyright (c) 2010-2024 Google LLC
dev,@eslint/js,MIT,Copyright OpenJS Foundation and other contributors, <www.openjsf.org>
dev,@jsdevtools/coverage-istanbul-loader,MIT,Copyright (c) 2015 James Messinger
dev,@ngtools/webpack,MIT,Copyright (c) 2017 Google LLC
dev,@playwright/test,Apache-2.0,Copyright Microsoft Corporation
dev,@salesforce/cli,Apache-2.0,Copyright (c) 2026 Salesforce, Inc.
Expand All @@ -38,6 +37,11 @@ dev,@typescript-eslint/utils,MIT,Copyright (c) 2019 typescript-eslint and other
dev,@wxt-dev/module-react,MIT,Copyright (c) 2023 Aaron
dev,@vitejs/plugin-react,MIT,Copyright (c) 2019-present Evan You & Vite Contributors
dev,@vitejs/plugin-vue,MIT,Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
dev,@vitest/browser,MIT,Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
dev,@vitest/browser-playwright,MIT,Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
dev,@vitest/browser-webdriverio,MIT,Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
dev,@vitest/coverage-istanbul,MIT,Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
dev,@vitest/ui,MIT,Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
dev,@microsoft/api-extractor,MIT,Copyright (c) Microsoft Corporation. All rights reserved.
dev,@module-federation/enhanced,MIT, Copyright (c) 2020 ScriptedAlchemy LLC (Zack Jackson) Zhou Shaw (zhouxiao)
dev,@vue/compiler-dom,MIT,Copyright (c) 2018-present, Yuxi (Evan) You
Expand All @@ -64,8 +68,6 @@ dev,jasmine-core,MIT,Copyright 2008-2017 Pivotal Labs
dev,json-schema-to-typescript,MIT,
dev,karma,MIT,Copyright 2011-2019 Google Inc.
dev,karma-browserstack-launcher,MIT,Copyright 2011-2013 Google, Inc.
dev,karma-chrome-launcher,MIT,Copyright 2011-2013 Google Inc.
dev,karma-coverage-istanbul-reporter,MIT,Copyright 2017 Matt Lewis
dev,karma-jasmine,MIT,Copyright 2011-2013 Google Inc.
dev,karma-junit-reporter,MIT,Copyright (C) 2011-2013 Google, Inc.
dev,karma-sourcemap-loader,MIT,Copyright 2013 Sergey Todyshev
Expand All @@ -92,9 +94,11 @@ dev,typescript,Apache-2.0,Copyright Microsoft Corporation
dev,typescript-eslint,MIT,Copyright (c) 2019 typescript-eslint and other contributors
dev,undici,MIT,Copyright (c) Matteo Collina and Undici contributors
dev,vite,MIT,Copyright (c) 2019-present, VoidZero Inc. and Vite contributors
dev,vitest,MIT,Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors
dev,vue,MIT,Copyright (c) 2018-present, Yuxi (Evan) You
dev,nuxt,MIT,Copyright (c) 2016-present Nuxt Team
dev,vue-router,MIT,Copyright (c) 2019-present Eduardo San Martin Morote
dev,webdriverio,MIT,Copyright (c) OpenJS Foundation and other contributors
dev,webpack,MIT,Copyright JS Foundation and other contributors
dev,webpack-cli,MIT,Copyright JS Foundation and other contributors
dev,webpack-dev-middleware,MIT,Copyright JS Foundation and other contributors
Expand Down
14 changes: 8 additions & 6 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,20 @@ Use this strategy to test the integration on Real applications.

## Work with unit tests

Unit tests run in Playwright's Chromium: install it once with `yarn playwright install chromium` (`yarn test:e2e:setup` also does it).

1. Write a unit test.
2. Run only your tests by temporarily replacing `describe(...)` with `fdescribe(...)` or `it(...)` with `fit(...)`.
3. Run `yarn test` in the project root. It will launch the tests in watch mode, and also expose [a local URL](http://localhost:9876/) that you can open in any browser.
2. Run `yarn test <path/to/your.spec.ts>` in the project root. It launches the tests in watch mode in a headless Chromium.
3. To narrow down further, temporarily replace `describe(...)` with `fdescribe(...)` or `it(...)` with `fit(...)` (this only applies within the selected files).
4. Look at your terminal to see your test results.
5. For deeper investigation, open [the "debug" page](http://localhost:9876/debug.html#) to inspect test execution via the devtools.
5. For deeper investigation, run `yarn test:unit:watch --browser.headless=false <path>` to open the browser and inspect test execution via the devtools.

## Debug flaky unit tests

Top-level `describe` blocks are run in a random order. Sometimes, an issue can only be reproduced with a given order. To reproduce a test run order:
Test files and tests are run in a random order. Sometimes, an issue can only be reproduced with a given order. To reproduce a test run order:

1. Check the `Randomized with seed XXXX` message from the test output.
2. Run `yarn test:unit --seed XXXX`.
1. Check the `Running tests with seed XXXX` message from the test output.
2. Run `yarn test:unit --sequence.seed=XXXX`.

## Work with E2E tests

Expand Down
14 changes: 9 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
"dev-server": "node scripts/dev-server/index.ts",
"release": "node ./scripts/release/prepare-release.ts --push",
"test": "yarn test:unit:watch",
"test:unit": "karma start ./test/unit/karma.local.conf.js",
"test:unit": "vitest run --config test/unit-vitest/vite.config.ts",
"test:script": "node --test --experimental-test-module-mocks './scripts/**/*.spec.*'",
"test:unit:watch": "yarn test:unit --no-single-run",
"test:unit:watch": "vitest --config test/unit-vitest/vite.config.ts",
"test:unit:bs": "node --env-file-if-exists=.env ./scripts/test/bs-wrapper.ts karma start test/unit/karma.bs.conf.js",
"test:e2e:setup": "yarn build && yarn build:apps && yarn playwright install --with-deps",
"test:e2e:setup:pinned": "volta run --node 20 yarn dlx -p playwright@1.40.1 playwright install chromium firefox webkit",
Expand All @@ -48,7 +48,6 @@
"devDependencies": {
"@datadog/rum-events-format": "DataDog/rum-events-format#commit=099b70ec2255f45ee4a557c53bd509694cd86212",
"@eslint/js": "10.0.1",
"@jsdevtools/coverage-istanbul-loader": "3.0.5",
"@microsoft/api-extractor": "7.60.1",
"@playwright/test": "1.64.1",
"@salesforce/cli": "2.157.7",
Expand All @@ -62,6 +61,11 @@
"@types/node-forge": "1.3.14",
"@types/ws": "8.18.2",
"@typescript-eslint/utils": "8.72.1",
"@vitest/browser": "4.1.8",
"@vitest/browser-playwright": "4.1.8",
"@vitest/browser-webdriverio": "4.1.8",
"@vitest/coverage-istanbul": "4.1.8",
"@vitest/ui": "4.1.8",
"ajv": "8.20.0",
"browserstack-local": "1.5.16",
"busboy": "1.6.0",
Expand All @@ -82,8 +86,6 @@
"json-schema-to-typescript": "bcaudan/json-schema-to-typescript#bcaudan/add-readonly-support",
"karma": "6.4.4",
"karma-browserstack-launcher": "1.6.0",
"karma-chrome-launcher": "3.2.0",
"karma-coverage-istanbul-reporter": "3.0.3",
"karma-jasmine": "4.0.2",
"karma-junit-reporter": "2.0.1",
"karma-sourcemap-loader": "0.4.0",
Expand All @@ -102,6 +104,8 @@
"typescript": "6.0.3",
"typescript-eslint": "8.72.1",
"undici": "8.12.3",
"vitest": "4.1.8",
"webdriverio": "9.27.2",
"webpack": "5.112.2",
"webpack-cli": "7.3.1",
"webpack-dev-middleware": "8.6.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { disableJasmineUncaughtExceptionTracking, wait } from '../../../test'
import { disableJasmineUncaughtExceptionTracking, registerCleanupTask, wait } from '../../../test'
import type { UnhandledErrorCallback } from './trackRuntimeError'
import { instrumentOnError, instrumentUnhandledRejection, trackRuntimeError } from './trackRuntimeError'
import type { RawError } from './error.types'
Expand Down Expand Up @@ -50,7 +50,15 @@ describe('instrumentOnError', () => {
const ERROR_MESSAGE = 'foo'

const spyViaInstrumentOnError = async (callback: () => void) => {
const onErrorSpy = spyOn(window as any, 'onerror')
// Replace the handler instead of spying on it: with Karma, `disableJasmineUncaughtExceptionTracking`
// restores Jasmine's handler in a cleanup task, which runs before Jasmine restores its spies (it
// would then put back the disabled handler)
const onErrorSpy = jasmine.createSpy('onerror')
const originalOnError = window.onerror
window.onerror = onErrorSpy
registerCleanupTask(() => {
window.onerror = originalOnError
})
const callbackSpy = jasmine.createSpy<UnhandledErrorCallback>()
const { stop } = instrumentOnError(callbackSpy)

Expand All @@ -63,6 +71,8 @@ describe('instrumentOnError', () => {
}
}

beforeEach(disableJasmineUncaughtExceptionTracking)

it('should call original error handler', async () => {
// withInstrumentOnError() asserts that the original error handler has been called for
// every test, so we don't need an explicit expectation here.
Expand Down Expand Up @@ -288,6 +298,8 @@ describe('instrumentUnhandledRejection', () => {
}
}

beforeEach(disableJasmineUncaughtExceptionTracking)
Comment thread
thomas-lebeau marked this conversation as resolved.
Resolved

it('should call original unhandled rejection handler', async () => {
// withInstrumentOnUnhandledRejection() asserts that the original unhandled
// rejection handler has been called for every test, so we don't need an
Expand Down
37 changes: 22 additions & 15 deletions packages/browser-core/src/tools/serialisation/sanitize.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -234,15 +234,19 @@ describe('sanitize', () => {
it('should not use toJSON methods added to arrays and objects prototypes', () => {
const toJSONArray = jasmine.createSpy('toJSONArray', () => 'Array').and.callThrough()
const toJSONObject = jasmine.createSpy('toJSONObject', () => 'Object').and.callThrough()
// Remove them before the test ends, even if it fails: Vitest's messages to its server are
// garbled while they are defined (see `jsonStringify.spec.ts`)
;(Array.prototype as any).toJSON = toJSONArray
;(Object.prototype as any).toJSON = toJSONObject

const arr = [{ a: 1, b: 2 }]
expect(sanitize(arr)).toEqual([{ a: 1, b: 2 }])
expect(toJSONArray).toHaveBeenCalledTimes(0)
expect(toJSONObject).toHaveBeenCalledTimes(0)
delete (Array.prototype as any).toJSON
delete (Object.prototype as any).toJSON
try {
const arr = [{ a: 1, b: 2 }]
expect(sanitize(arr)).toEqual([{ a: 1, b: 2 }])
expect(toJSONArray).toHaveBeenCalledTimes(0)
expect(toJSONObject).toHaveBeenCalledTimes(0)
} finally {
delete (Array.prototype as any).toJSON
delete (Object.prototype as any).toJSON
}
})

it('should survive a faulty toJSON', () => {
Expand All @@ -258,15 +262,18 @@ describe('sanitize', () => {
it('should restore prototype toJSON methods when sanitization throws', () => {
const toJSON = jasmine.createSpy('toJSON', () => 'Object').and.callThrough()
;(Object.prototype as any).toJSON = toJSON
const obj = {
get x() {
throw new Error('Cannot sanitize')
},
}
try {
const obj = {
get x() {
throw new Error('Cannot sanitize')
},
}

expect(() => sanitize(obj)).toThrowError('Cannot sanitize')
expect(Object.prototype.hasOwnProperty.call(Object.prototype, 'toJSON')).toBe(true)
delete (Object.prototype as any).toJSON
expect(() => sanitize(obj)).toThrowError('Cannot sanitize')
expect(Object.prototype.hasOwnProperty.call(Object.prototype, 'toJSON')).toBe(true)
} finally {
delete (Object.prototype as any).toJSON
}
})
})

Expand Down
11 changes: 7 additions & 4 deletions packages/browser-core/test/consoleLog.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
const ignoreList: Array<{ level: string; match: string }> = []
import { registerCleanupTask } from './registerCleanupTask'

afterEach(() => {
ignoreList.length = 0
})
const ignoreList: Array<{ level: string; match: string }> = []

/**
* Ignore console logs that match the given level and message for the duration of the test. This
* function can be called multiple times to ignore multiple logs.
*/
export function ignoreConsoleLogs(level: 'error' | 'warn' | 'log', match: string) {
if (ignoreList.length === 0) {
registerCleanupTask(() => {
ignoreList.length = 0
})
}
ignoreList.push({ level, match })

// eslint-disable-next-line @typescript-eslint/unbound-method
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
import { noop } from '@datadog/js-core/util'
import { registerCleanupTask } from './registerCleanupTask'

/**
* Disable Jasmine's uncaught error handling. This is useful for test cases throwing exceptions or
* unhandled rejections that are expected to be caught somehow, but Jasmine also catch them and
* fails the test.
*
* Replace the handler instead of spying on it, so tests can still replace `window.onerror`. Tests
* must not spy on it after calling this: Jasmine restores spies after the cleanup tasks run, so it
* would put back the disabled handler.
*
* This is the Karma implementation. When running with Vitest, this module is aliased to
* `test/unit-vitest/disableJasmineUncaughtExceptionTracking.ts` (see `test/unit-vitest/vite.config.ts`).
*/
export function disableJasmineUncaughtExceptionTracking() {
spyOn(window as any, 'onerror')
const originalOnError = window.onerror
window.onerror = noop
registerCleanupTask(() => {
window.onerror = originalOnError
Comment thread
thomas-lebeau marked this conversation as resolved.
Resolved
Comment thread
thomas-lebeau marked this conversation as resolved.
Resolved
})
}
10 changes: 6 additions & 4 deletions packages/browser-core/test/emulate/mockReportingObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,13 @@ export type MockCspEventListener = ReturnType<typeof mockCspEventListener>
export function mockCspEventListener() {
// eslint-disable-next-line @typescript-eslint/unbound-method
const originalAddEventListener = EventTarget.prototype.addEventListener
EventTarget.prototype.addEventListener = jasmine
.createSpy()
.and.callFake((_type: string, listener: EventListener) => {
EventTarget.prototype.addEventListener = jasmine.createSpy().and.callFake(function (this: any, type, listener) {
if (type === 'securitypolicyviolation') {
listeners.push(listener)
})
} else {
originalAddEventListener.call(this, type, listener)
}
})

registerCleanupTask(() => {
EventTarget.prototype.addEventListener = originalAddEventListener
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,19 @@ import { resetInteractionCountPolyfill } from '../../browser-rum-core/src/domain
import { resetTelemetry } from '../src/domain/telemetry'
import { resetSampleDecisionCache } from '../src/domain/sampler'
import { startLeakDetection } from './leakDetection'
import { registerCleanupTask } from './registerCleanupTask'
;(window as any).IS_REACT_ACT_ENVIRONMENT = true

beforeEach(() => {
// Tests calling `history.pushState()` leave the shared page on another URL. Restore the full URL
// (Vitest's includes `?sessionId=…&iframeId=…`), so a page reload still lands on the test runner.
// Registered first, so it runs after the cleanup tasks of the test, which can change the URL too.
const urlBeforeTest = location.href
registerCleanupTask(() => {
if (location.href !== urlBeforeTest) {
history.replaceState(history.state, '', urlBeforeTest)
}
})
// prevent 'Some of your tests did a full page reload!' issue
window.onbeforeunload = () => 'stop'
startLeakDetection()
Expand Down
Loading
Loading