Skip to content

👷 [RUM-19776] Run unit tests with Vitest (Jasmine compatibility shim) instead of Karma - #5135

Merged
thomas-lebeau merged 18 commits into
mainfrom
thomas.lebeau/vitest-wip
Nov 12, 2026
Merged

thomas-lebeau merged 18 commits into
mainfrom
thomas.lebeau/vitest-wip

Conversation

@thomas-lebeau

@thomas-lebeau thomas-lebeau commented Oct 13, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

Karma is deprecated (RUM-19766). This PR switches the unit job from Karma to Vitest Browser Mode while keeping specs on the Jasmine API, through a compatibility shim. The runner changes first; specs can then be migrated to the Vitest API incrementally, package by package.

It builds on Benoît's experiment (#4720), brought up to date with main. A green CI here validates the approach on the whole suite. BrowserStack (unit-bs) stays on Karma in this PR; it moves to Vitest in #5136.

Comparison of the previous attempts: https://dd-quick.us1.staging.dog/browser-sdk-vitest-attempts/

Closes RUM-19776

Changes

Vitest setup (test/unit-vitest/)

  • Benoît's two commits, cherry-picked onto current main (authorship kept): Vitest Browser Mode (Playwright, headless Chromium) running specs unchanged through a jasmine-core based shim (spies, clock, matchers, done callbacks, pending()).
  • Adapted to current main (js-core entries, getBuildEnvDefines, createSpyObj, expectAsync).
  • Package aliases generated from tsconfig.base.json paths; Karma's /base/ fixture URLs still served.

yarn test:unit / CI unit now run Vitest on all 309 spec files, with Karma parity:

  • random file + test order (seed printed, --sequence.seed=<seed> to reproduce)
  • JUnit report in test-report/unit/ and istanbul coverage (clover) in coverage/unit/ in CI, picked up by export-test-result.ts
  • in CI, a test calling console.* without spying on it fails (same as karmaUnexpectedErrorLogReporterPlugin)

All test files share one page (isolate: false), like Karma did. Tests stay independent thanks to forEach.ts and registerCleanupTask(); reloading the page for every file was most of the run time. This required:

  • registering hooks from setup files (run for every test file) instead of at module evaluation: shim getCurrentJasmineSpec, and ignoreConsoleLogs now cleans up through registerCleanupTask()
  • not installing Jasmine's global error handlers in the shim: they forwarded unhandled rejections to window.onerror, reporting them twice and making trackRuntimeError.spec order-dependent
  • pre-bundling react/jsx-dev-runtime (injected by the JSX transform, invisible to Vite's scanner), so Vite doesn't reload the shared page mid-run

Other

  • Typecheck/lint fixes; Karma's disableJasmineUncaughtExceptionTracking replaces window.onerror instead of spying on it (cause of the 19 Karma failures on vitest migration #4720).
  • Removed the local Karma config and its dependencies (karma-chrome-launcher, karma-coverage-istanbul-reporter, @jsdevtools/coverage-istanbul-loader); new dev dependencies declared in LICENSE-3rdparty.csv.
  • Docs (AGENTS.md, docs/TESTING.md, .cursor rules): yarn test:unit <path> instead of --spec, --sequence.seed=<n> instead of --seed. Focused tests (fit/fdescribe) only apply within the selected files.

Results

unit job duration (CI Visibility, minutes):

Karma (other PRs, last 14 days) Vitest (this PR)
avg / p50 / p90 2.64 / 2.44 / 3.43 (n=420) 2.45, 2.80 (latest runs)

309/309 files and 5610/5610 tests pass after rebasing on main (2026-11-03); locally ~25s for the full suite (~50s with coverage).

⚠️ The adaptation, fix and migration commits were written with an AI agent (Claude Code).

Test instructions

yarn
yarn test:unit                                   # all specs on Vitest
yarn test:unit packages/browser-core/src/tools   # filter by path
yarn test:unit --sequence.seed=123               # reproduce an order
CI=true CI_JOB_NAME=unit yarn test:unit          # CI mode: coverage, junit, console check

Checklist

  • Tested locally
  • Tested on staging
  • Added unit tests for this change.
  • Added e2e/integration tests for this change.
  • Updated documentation and/or relevant AGENTS.md file

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Bundles Sizes Evolution

📦 Bundle Name Base Size Local Size 𝚫 𝚫% Status
Rum Salesforce 192.25 KiB 192.25 KiB 0 B 0.00% ✅
Rum 192.23 KiB 192.23 KiB 0 B 0.00% ✅
Rum Profiler 8.17 KiB 8.17 KiB 0 B 0.00% ✅
Rum Salesforce Profiler 8.17 KiB 8.17 KiB 0 B 0.00% ✅
Rum Salesforce Recorder 32.59 KiB 32.59 KiB 0 B 0.00% ✅
Rum Recorder 32.59 KiB 32.59 KiB 0 B 0.00% ✅
Logs 60.19 KiB 60.19 KiB 0 B 0.00% ✅
Rum Slim 148.16 KiB 148.16 KiB 0 B 0.00% ✅
Worker 24.23 KiB 24.23 KiB 0 B 0.00% ✅
Rum Shopify 223.27 KiB 223.27 KiB 0 B 0.00% ✅
Rum Shopify Profiler 8.17 KiB 8.17 KiB 0 B 0.00% ✅
Rum Shopify Recorder 4.85 KiB 4.85 KiB 0 B 0.00% ✅

@thomas-lebeau
thomas-lebeau added this pull request to stack #5137 October 13, 2026 15:42
@datadog-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
• Patch Coverage: 100.00%
• Overall Coverage: 78.04% (+0.54%)

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: edd8020 | Docs | View more details | Give us feedback!

@thomas-lebeau thomas-lebeau changed the title 👷 Vitest unit test setup with a Jasmine compatibility shim 👷 Run unit tests with Vitest (Jasmine compatibility shim) instead of Karma Oct 13, 2026
@thomas-lebeau
thomas-lebeau force-pushed the thomas.lebeau/vitest-wip branch from 890a70f to 9d43442 Compare October 14, 2026 11:54
@thomas-lebeau
thomas-lebeau force-pushed the thomas.lebeau/vitest-wip branch from 9d43442 to d08f8a8 Compare October 15, 2026 14:37
@thomas-lebeau
thomas-lebeau force-pushed the thomas.lebeau/vitest-wip branch from d08f8a8 to 19284f9 Compare November 3, 2026 11:34
@thomas-lebeau
thomas-lebeau marked this pull request as ready for review November 3, 2026 15:22
@thomas-lebeau
thomas-lebeau requested a review from a team as a code owner November 3, 2026 15:22
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-11T06:21:29.418041Z 758dce0 Draft marked ready
🔒 Security Review ✅ Completed 2026-11-11T06:23:04.366094Z 758dce0 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 77d3909e13

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread test/unit-vitest/vitest.setup.ts Resolved
Comment thread test/unit-vitest/vitest.setup.ts Resolved

@datadog-datadog-prod-us1 datadog-datadog-prod-us1 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: FAIL

The Jasmine shim can silently pass tests when explicit failures or failed assertions are caught. Cleanup ordering also leaves BrowserStack’s error handler disabled and lets final cleanup console output escape CI enforcement.

Open Bits AI session

🤖 Bits Code Review · Commit 77d3909

Comment thread test/unit-vitest/vitest.setup.ts Resolved
Comment thread test/unit-vitest/vitest.setup.ts Resolved
Comment thread test/unit-vitest/vitest.setup.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 22a3cfe86b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread test/unit-vitest/vitest.setup.ts Resolved
Comment thread packages/browser-core/test/forEach.ts Resolved
@thomas-lebeau
thomas-lebeau force-pushed the thomas.lebeau/vitest-wip branch from 22a3cfe to f73f301 Compare November 3, 2026 20:45

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 473891bc84

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread test/unit-vitest/vitest.setup.ts Resolved
Comment thread test/unit-vitest/allJsonSchemas.ts Resolved
@thomas-lebeau
thomas-lebeau force-pushed the thomas.lebeau/vitest-wip branch from 473891b to 42dc244 Compare November 4, 2026 14:35

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 42dc244db7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread test/unit-vitest/vite.config.ts Resolved
Comment thread test/unit-vitest/vitest.setup.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 67289c617c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread test/unit-vitest/vite.config.ts Resolved
Comment thread test/unit-vitest/vite.config.ts Resolved
Comment thread test/unit-vitest/vitest.setup.ts Resolved
@thomas-lebeau thomas-lebeau changed the title 👷 Run unit tests with Vitest (Jasmine compatibility shim) instead of Karma 👷 [RUM-19776] Run unit tests with Vitest (Jasmine compatibility shim) instead of Karma Nov 5, 2026
@thomas-lebeau
thomas-lebeau marked this pull request as draft November 10, 2026 15:31
@thomas-lebeau
thomas-lebeau force-pushed the thomas.lebeau/vitest-wip branch from c4d08d2 to 280d450 Compare November 10, 2026 15:40
BenoitZugmeyer and others added 6 commits November 11, 2026 05:35
- map @datadog/js-core/* entries (package added after the experiment)
- use getBuildEnvDefines (buildEnv API changed)
- support jasmine.createSpyObj and expectAsync in the jasmine shim
- typecheck vitest config files as node code (tsconfig.scripts.json)
- add vite/client types for import.meta.glob and a jasmine-core declaration
- load forEach.ts as a setup file instead of a top-level await
- disable unsafe-* lint rules in the jasmine shim (jasmine-core is untyped)
- karma: make disableJasmineUncaughtExceptionTracking replace window.onerror
  instead of spying on it, so tests calling it can still spy on onerror
`yarn test:unit` (and the CI `unit` job) now runs every spec on Vitest
Browser Mode (headless Chromium) through the Jasmine shim. BrowserStack
(`unit-bs`) stays on Karma.

- resolve package entry points from tsconfig.base.json `paths`
- serve Karma's `/base/` fixture URLs
- random file/test order (`--sequence.seed` to reproduce)
- junit report in test-report/unit and istanbul coverage in coverage/unit
  (CI), consumed by export-test-result.ts
- fail tests calling console methods without spying on them (CI), like
  karmaUnexpectedErrorLogReporterPlugin
- remove the local karma config and its dependencies
- update docs for the new CLI
thomas-lebeau and others added 11 commits November 11, 2026 05:35
Like Karma, run all test files in the same page: tests are kept independent
by forEach.ts and `registerCleanupTask()`, and reloading the page for each
file was most of the run time (local run: ~28s -> ~15s).

- register hooks from setup files (run for every test file) instead of at
  module evaluation, which only applies to the first test file when modules
  are shared: shim `getCurrentJasmineSpec`, `ignoreConsoleLogs` cleanup
- don't install Jasmine's global error handlers in the shim: they forwarded
  unhandled rejections to `window.onerror`, reporting them twice and making
  trackRuntimeError.spec order-dependent
…page

The JSX transform injects react/jsx-dev-runtime, which the dependency
scanner can't see: Vite discovered it mid-run and reloaded the page, which
made every following test file fail when files share the page.
…lpers

The first `trackRuntimeError` describe already disables uncaught exception
tracking inside `errorViaTrackRuntimeError`, so its `beforeEach` was redundant.
The `instrumentOnError` and `instrumentUnhandledRejection` ones are still
needed: without them, Vitest reports unhandled errors and fails the run.

Explain in both `disableJasmineUncaughtExceptionTracking` implementations
why there is a Karma and a Vitest one, and how the alias swaps them.

Environment: Datadog workspace

Co-Authored-By: Claude Code claude-sonnet-5-5 <noreply@anthropic.com>
With `isolate: false`, all test files share one page, so a test calling
`history.pushState()` leaves it on another URL. Some specs don't restore it
(`urlPolyfill.spec.ts`), others only restore the pathname, dropping Vitest's
`?sessionId=…&iframeId=…` query. If the page reloads afterwards (e.g. the Vite
client reloading after its websocket reconnects on BrowserStack), it lands on
the wrong URL and Vitest fails with "Cannot connect to the iframe".

Restore the full URL in the global `afterEach`.

Environment: Datadog workspace

Co-Authored-By: Claude Code claude-opus-5-5 <noreply@anthropic.com>
…er cleanups

Address review feedback on the Vitest Jasmine shim:

- Define Jasmine's global `fail()`. It was missing, so `fail()` threw a
  ReferenceError that specs like `readBytesFromStream.spec.ts` caught and
  accepted as the expected error.
- Record failed expectations (and `fail()`) before throwing, like Jasmine with
  `stopSpecOnExpectationFailure`, and fail the test when one was caught by the
  code under test (ex: `callMonitored(() => expect(...))`).
- Check unexpected console calls in `onTestFinished`, after
  `registerCleanupTask()` tasks. With `isolate: false` the setup file runs again
  for each spec file in the same page, so patch the console once and share the
  calls across files instead of losing calls made between two files.
- In `trackRuntimeError.spec.ts`, replace `window.onerror` instead of spying on
  it: with Karma, Jasmine restored the spy after the cleanup task, which put
  back the disabled handler and left uncaught error tracking off for the
  following specs.

Environment: Datadog workspace

Co-Authored-By: Claude Code claude-sonnet-5-5 <noreply@anthropic.com>
With Vitest, `registerCleanupTask()` callbacks run in `onTestFinished`, after
`afterEach` hooks, so a cleanup calling `history.pushState()` (ex:
`locationChangeObservable.spec.ts`) undid the URL restoration in `forEach.ts` and
dropped Vitest's `sessionId` and `iframeId` query parameters for the next tests.
Register the restoration as the first cleanup task of the test instead, so it
runs after the test's own cleanup tasks, with both Vitest and Karma.

Environment: Datadog workspace

Co-Authored-By: Claude Code claude-opus-5-5 <noreply@anthropic.com>
Vitest sends messages from the test page to its server serialized with
`JSON.stringify`: while `Object.prototype` (or `Array.prototype`) has a `toJSON`
method, those messages are garbled (an object serializes as "42"), and a lost
message can stall the run (reproduced locally). `jsonStringify.spec.ts` defined
such methods in the test body and only removed them in `afterEach`, after
Vitest's async steps between the test and its hooks. This failed BrowserStack
runs with "Browser connection was closed while running tests" in this spec.

Define them for the time of a synchronous callback instead, and make
`sanitize.spec.ts` remove them even when an expectation fails.

Environment: Datadog workspace

Co-Authored-By: Claude Code claude-opus-5-5 <noreply@anthropic.com>
…t the Chromium install

- Vitest 4 runs setup files in parallel by default, while forEach.ts uses the
  Jasmine globals defined by vitest.setup.ts: run them in list order.
- Karma instrumented developer-extension sources for coverage too: include
  them.
- Unit tests now run in Playwright's Chromium, which a fresh checkout doesn't
  have (only `yarn test:e2e:setup` installed it): document installing it.

Environment: Datadog workspace

Co-Authored-By: Claude Code claude-opus-5-5 <noreply@anthropic.com>
Collecting coverage for `developer-extension/src` made Vitest load every
extension file to report the uncovered ones, including the entry points that
import `wxt`. Vite then bundled `wxt` in the middle of the run, which made the
`unit` job run out of memory. Only collect coverage for `packages/*/src`, as
before.

Environment: Datadog workspace

Co-Authored-By: Claude Code claude-opus-5-5 <noreply@anthropic.com>
@thomas-lebeau
thomas-lebeau force-pushed the thomas.lebeau/vitest-wip branch from ef8d68b to 758dce0 Compare November 11, 2026 05:36
@thomas-lebeau
thomas-lebeau marked this pull request as ready for review November 11, 2026 06:19

@datadog-datadog-prod-us1 datadog-datadog-prod-us1 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: FAIL

CI coverage now counts 11 existing test helpers as application code because the new exclusion glob no longer matches their filenames.

Open Bits AI session

🤖 Bits Code Review · Commit 758dce0

Comment thread test/unit-vitest/vite.config.ts Resolved
Karma excluded every file whose name ends in `specHelper.ts` or
`capturedExceptions.ts`, but the Vitest globs only matched those exact
basenames. All `*.specHelper.ts` helpers were then reported as application
code in the coverage report. Match by suffix again, as Karma did.

Environment: Datadog workspace

Co-Authored-By: Claude Code claude-sonnet-5-5 <noreply@anthropic.com>

@datadog-datadog-prod-us1 datadog-datadog-prod-us1 Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bits Code Review: PASS

More details

The PR moves local and CI unit tests to Vitest Browser Mode with a Jasmine shim; BrowserStack remains on Karma. The new suffix globs restore coverage exclusions for all 11 test helpers, resolving the earlier finding; no reportable issues remain open.

Was this helpful? React 👍 or 👎

Open Bits AI session

🤖 Bits Code Review · Commit edd8020

@thomas-lebeau
thomas-lebeau merged commit 1cc8400 into main Nov 12, 2026
31 checks passed
@thomas-lebeau
thomas-lebeau deleted the thomas.lebeau/vitest-wip branch November 12, 2026 06:03
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 12, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants