12k
All articles

Speeding Up Your Test Suite with vitest doctor

Use vitest doctor to compare test-suite configurations, interpret timing reports, and verify pool, isolation, and DOM environment recommendations before updating Vitest.

OpenReplay Team
OpenReplay Team
Speeding Up Your Test Suite with vitest doctor

vitest doctor runs your full test suite under your current configuration and under a set of alternative configurations, reports how long each one took relative to the baseline, and prints a recommended vitest.config.ts snippet.

Many projects reach the same point eventually: a jsdom suite with a few hundred files that takes far too long in CI, and nobody on the team has ever changed pool or isolate. Doctor arrived in Vitest 5.0, alongside the other changes covered in What Changed in Vitest 5. This article covers how to run it, how to read its report, what each suggested setting gives up in exchange for speed, and how to confirm a suggestion before you commit it. The behaviour described here matches the CLI documentation for Vitest 5.1.0.

Key Takeaways

  • vitest doctor needs a passing suite. If the baseline fails, it aborts and shows the errors instead of measuring anything.
  • Doctor runs the full suite at least once per candidate, so it takes several times longer than a normal vitest run. Treat it as an on-demand tool, not a CI step.
  • Doctor only recommends isolate: false after two runs with shuffled file order, and it prefers configurations that keep per-file isolation when results are close.
  • The Vitest performance guide estimates jsdom setup at roughly 200–500 ms per import and happy-dom at 90–200 ms, a cost paid once per file under isolating pools.

What Does vitest doctor Do?

vitest doctor replaces guesswork with measurement. According to the CLI docs, it runs the suite under each alternative configuration to measure how much time each one would save. It builds the list of candidates from your current config, times each one against your baseline, and ends with one recommendation you can paste into your config.

The performance hints that Vitest prints after a run are a different thing. Hints are inferred from timings collected during a normal run. Doctor actually runs every alternative.

Running Doctor: A Green Suite and Time

Run vitest doctor from the project root:

npx vitest doctor

vitest doctor has two prerequisites: a passing suite and time. First, the suite has to pass. If it fails under the current configuration, doctor stops and prints the errors, since it has no passing baseline to compare candidates with. Fix or skip failing tests first. Second, it takes time: because doctor repeats the full suite for every candidate, a doctor run lasts several times longer than a normal vitest run. Run it locally or in a one-off CI job, not on every push.

How Do You Read the vitest doctor Report?

The vitest doctor report lists the baseline first, labelled with your current pool and isolation settings. Each candidate follows with its wall-clock time and its percentage change from the baseline. The sample report in the docs is headed “min of 3 runs each”, and the docs explain that short suites are measured several times with the best time reported, so the comparison reflects a warm steady state. After the timings come a recommendation and a ready-to-paste config snippet. A failing candidate is reported with an excerpt of its errors instead of a time. Doctor measures and reports the baseline even when there are no candidates to compare.

The recommended line is not always the fastest one. If more than one candidate lands near the fastest time, doctor picks the one that still isolates each file. A small gain from dropping isolation is not worth the risk of tests leaking state into each other.

Which Settings Can Doctor Suggest?

Every setting vitest doctor can suggest trades something away for speed. The table summarises each one, and the notes below cover the details.

SettingWhen doctor tries itWhat can break
pool: 'threads'Default forks poolNative modules or code that expects a separate process
isolate: falseIsolation is onModule state and mocks leak between files
pool: 'vmThreads' / 'vmForks'DOM or custom environmentsinstanceof across realms, memory growth
environment: 'happy-dom'jsdom projects with happy-dom installedLayout and navigation behaviour
fsModuleCache: trueThe cache is offLittle; it is the default
Lower maxWorkersProbed on the winning configLess parallelism on smaller machines

Pool. forks is the default pool and the more compatible choice. The performance guide says threads may be slightly faster in larger projects.

Isolation. Turning isolation off removes the per-file environment and module reset. Doctor only offers it after running the suite twice with shuffled file order, and it marks the candidate as failed if any test depends on a clean start. That check catches order dependence, but it cannot catch every kind of shared-state bug. Module-level mocks are the usual victim, so review your mocking patterns (see mocking API calls in Vue tests with Vitest) before you accept the suggestion.

vm pools. The vm pools create the DOM environment once per worker and give each test file a fresh VM context. This removes most of the per-file jsdom cost. The trade-off is that your code runs in a separate realm, where instanceof checks against externalized packages can fail and memory is reclaimed less reliably. vmMemoryLimit caps how much memory a worker can use before it is replaced. vmForks runs each worker as a child process with its own heap, which suits suites that cannot use worker threads.

happy-dom. Doctor only tries happy-dom for projects that use jsdom and already have happy-dom installed. The two libraries implement the DOM differently, so tests that rely on layout or navigation need checking before the swap is kept.

fsModuleCache. This persists transformed modules on disk between runs. It is on by default, so doctor only suggests it if you have turned it off.

maxWorkers. All workers request transforms from one Vite server on the main thread, so more workers can mean more contention. Doctor starts at half your current worker count and keeps halving it as long as each step makes the suite at least 5% faster. The best value goes into the recommendation.

Test a Suggestion Before Keeping It

A doctor recommendation is a measurement taken on one machine at one point in time. Verify it before you merge.

  1. Paste the snippet into vitest.config.ts.
  2. Run npx vitest run several times and compare the wall-clock times.
  3. If the suggestion is isolate: false, shuffle the file order with a few different seeds.
  4. If the suggestion is happy-dom, rerun the tests that touch layout or navigation and read each failure closely.

Here is what an applied vm-pool suggestion looks like:

// vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    environment: 'jsdom',
    pool: 'vmThreads', // suggested by vitest doctor; re-verify after upgrades
  },
})

To check isolate: false yourself, run the suite with isolation off and file order shuffled, using a different seed each time:

npx vitest run --no-isolate --sequence.shuffle.files --sequence.seed=1
npx vitest run --no-isolate --sequence.shuffle.files --sequence.seed=2

If only some files fail without isolation, you don’t have to choose all or nothing. Vitest’s per-file isolation recipe shows how to use projects to keep isolation for most files and turn it off only for files that pass these runs.

Tips That Apply Regardless

Some Vitest speed-ups don’t depend on doctor at all. Start by reading the Duration line at the end of each run. Its percentages are shares of the summed phase time, not of wall-clock time.

Largest phaseWhere to look
environmentvm pools, happy-dom, node environment for non-DOM files
importBarrel files, heavy modules imported in every file
transformfsModuleCache, NODE_COMPILE_CACHE
testsYour test code

If the tests phase dominates, the time is going into your test code itself, and no pool or isolation setting will recover much of it.

Under an isolating pool, every file re-imports its whole dependency graph. That makes barrel index.ts re-exports and heavy modules in a shared setup file expensive, because the cost repeats in every file. Import from specific files instead. Setting test.dir also narrows the directory Vitest scans for test files.

DOM setup is a per-file cost too. The guide estimates jsdom at roughly 200–500 ms per import and happy-dom at 90–200 ms. Use projects to run non-DOM files in the node environment:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    projects: [
      { test: { name: 'logic', include: ['src/**/*.node.test.ts'], environment: 'node' } },
      { test: { name: 'ui', include: ['src/**/*.test.tsx'], environment: 'jsdom' } },
    ],
  },
})

Finally, shard in CI. The single main-thread Vite server that limits maxWorkers also limits how far one large machine can scale, so splitting the suite across several machines helps. Sharding splits the work by test file:

npx vitest run --reporter=blob --shard=1/3   # one per CI job
npx vitest run --merge-reports              # after collecting every job's blob report

Conclusion

Doctor gives you measured timings for configurations you would otherwise have to guess at. Its recommendations are still hypotheses until you have verified them on your own suite. Get the suite green, run npx vitest doctor once, then apply the snippet and rerun it with shuffled order and DOM-sensitive tests before merging. If your Vitest setup is also moving to a unified toolchain, the companion guide How to Migrate an Existing Project to Vite+ covers that step.

FAQs

Can I use vitest doctor on Vitest 4?

No. The vitest doctor command was introduced in Vitest 5.0, so you need to upgrade first. Vitest 5 requires Vite 6.4.0 or later and Node.js 22.12.0 or later, and the migration guide lists breaking changes to review before upgrading. On Vitest 4, you can still test pool, isolation and environment changes by hand with the levers in the Vitest performance guide.

Does vitest doctor include Browser Mode projects in its measurements?

Yes. Every measurement runs the full suite, browser projects included, so a suite with Browser Mode projects pays that cost again for each candidate. The isolate: false candidate also affects browser mode, which means turning isolation off changes how browser tests run too, not just Node-side tests. Check your browser tests for shared state before you accept an isolate: false recommendation.

Why might the fsModuleCache result from vitest doctor not match my first CI run?

Doctor measures fsModuleCache: true after an untimed priming run that fills the cache, so the time it reports is what repeated runs pay once the cache is warm. A CI runner that starts with an empty cache on every job pays the full transform cost on that first run. You only see the reported gain if the cache survives between runs.

Does vitest doctor switch every project to happy-dom in a multi-project setup?

No. Doctor applies the happy-dom swap per project. Only projects running jsdom are measured under environment: 'happy-dom', and only when the happy-dom package is installed. Projects on other environments, such as node, keep their existing environment during that measurement. Before you keep the swap, check the jsdom projects for tests that depend on layout or navigation.

DevTools for the frontend

Gain Debugging Superpowers

Unleash the power of session replay to reproduce bugs, track slowdowns and uncover frustrations in your app. Get complete visibility into your frontend with OpenReplay — the most advanced open-source session replay tool for developers.

Star on GitHub12k

We use cookies to improve your experience. By using our site, you accept cookies.