The Analogy: The Dress Rehearsal on the Real Set
A dress rehearsal earns its name by happening on the actual stage, with the scenery the scene shop already built for opening night, lit by the real rig and run by the real crew - the cast is not miming against folding chairs and taped floor-marks that stand in for a set that will exist only later. Vitest is that rehearsal: it runs your tests through the very same build pipeline that serves the app - the same scene shop that assembles each piece (the transform that strips TypeScript and compiles JSX), the same prop master who knows where every borrowed item is stored (the resolver and its aliases), the same standing crew notes (your plugins) - so a module is built and located in a test exactly as it is in the running app.
The theatre keeps ONE prop master and ONE scene shop, and both the rehearsal and the performance draw from them, so the afternoon a designer moves a prop to a new shelf the change reaches the rehearsal and the show at once; nobody keeps a second, parallel inventory that still lists the prop on its old shelf. That single source is the whole economy of the arrangement: your aliases, your TypeScript and JSX handling, your CSS and asset rules are written down once in the Vite config, and the test block sits inside that same config instead of restating any of it - add an alias in the morning and the rehearsal finds the prop the same afternoon the show can.
A rehearsal does not always need the full stage: a scene that is two actors talking can be worked in a bare rehearsal room, while a scene with the flying rig, the trap door, and the revolving floor has to be run on the fully dressed stage or it proves nothing at all. test.environment is exactly that choice - node is the bare room, enough for pure logic that never touches a browser, and jsdom is the dressed stage that hands the code a document, a window, and the DOM machinery a component test leans on - and you pick it per suite rather than dressing every rehearsal as though it needed the flying rig.
But the most flawless dress rehearsal only ever proves the blocking and the lines; it says nothing about whether the costumes will be finished in time or whether the box-office till will balance on opening night, because none of that was ever on the rehearsal-room floor to be checked. A green Vitest run is bounded in the same way: it exercises the transformed dev pipeline, so it can no more vouch for the production Rollup build than a rehearsal can vouch for the front-of-house, and it strips types the way Vite does, so it never checks them - the reassurance it gives is real but partial, and reading it as "the whole production is ready to open" is precisely how a passing suite comes to sit beside a broken vite build.
Syntax or Core Structure
Vitest is configured in the same file as Vite. You import defineConfig from vitest/config (not from vite) so the extra test key is typed, and that test block sits directly alongside plugins and resolve:
import { defineConfig } from 'vitest/config'
import react from '@vitejs/plugin-react'
import path from 'node:path'
export default defineConfig({
plugins: [react()],
resolve: {
alias: { '@': path.resolve(__dirname, './src') },
},
test: {
environment: 'node', // 'jsdom' only for suites that touch the DOM
globals: false, // import test/expect explicitly
},
})
There is no second resolver to configure and no second list of transforms: plugins and resolve are the ones the app already uses, and the test files pass through them unchanged. The single most important consequence is that an import resolves the same way on both sides. A tiny resolver modelling one shared alias map, called once as the app and once as a test, makes that concrete:
// One resolver, one alias map. The app and its tests both call it, so a module
// resolves in a test exactly as it resolves in the running app - there is no
// second alias table to drift from the first.
const alias = { '@': '/project/src' };
function resolveImport(spec) {
for (const key of Object.keys(alias)) {
if (spec === key || spec.startsWith(key + '/')) {
return alias[key] + spec.slice(key.length);
}
}
return spec; // a bare package id is left for node_modules
}
const imports = [
['app', '@/lib/format'],
['test', '@/lib/format'],
['app', '@/config/constants'],
['test', '@/config/constants'],
['app', 'react'],
];
for (const [side, spec] of imports) {
console.log(side.padEnd(4) + ' ' + spec.padEnd(20) + ' -> ' + resolveImport(spec));
}
Output:
app @/lib/format -> /project/src/lib/format
test @/lib/format -> /project/src/lib/format
app @/config/constants -> /project/src/config/constants
test @/config/constants -> /project/src/config/constants
app react -> react
The app and test rows are identical because they are literally the same function reading the same map: @/lib/format becomes /project/src/lib/format for both, and a bare react is left untouched for Node to find in node_modules. Nothing in the test re-declared the @ alias, which is the property the rest of this lesson depends on.
Technical Depth: How Vitest Reuses the Config and Where That Stops
The test block and how vitest.config merges
The test block is not a separate program; it is one more key in the config object the app already exports. Everything outside it - plugins, resolve, define - applies to test files with no restatement:
| Setting | Where it lives | Reused by tests |
|---|---|---|
| Path aliases | resolve.alias | Yes, the same map |
| JSX / TypeScript | plugins / esbuild | Yes, the same transform |
| CSS + asset imports | Vite core pipeline | Yes |
| Env vars | .env + define | Yes, the same values |
| Test-only options | test block | Test config only |
You can keep the block in vite.config.ts, or move it to a dedicated vitest.config.ts; when both exist Vitest MERGES them rather than replacing, so a separate test file adds to the Vite config instead of shadowing it. Importing defineConfig from vitest/config is what types the test key - importing from vite leaves test untyped and silently unchecked. The value of that single source shows up the moment an alias changes: with two separate resolvers, adding one to the app config leaves the other behind, while a shared map cannot fall out of step with itself.
// Two pipelines = two alias maps = two sources of truth. Add an alias to one
// and the other silently falls behind. One shared map cannot drift from itself.
function makeResolver(alias) {
return (spec) => {
for (const key of Object.keys(alias)) {
if (spec === key || spec.startsWith(key + '/')) return alias[key] + spec.slice(key.length);
}
return null; // unresolved
};
}
// A colleague adds '@hooks' to the APP config only.
const appAlias = { '@': '/src', '@hooks': '/src/hooks' };
const testAlias = { '@': '/src' }; // the second, drifted copy
const twoApp = makeResolver(appAlias);
const twoTest = makeResolver(testAlias);
const shared = makeResolver(appAlias); // one map, both sides call it
function show(side, resolve) {
const r = resolve('@hooks/useCart');
console.log(' ' + (side + ' import').padEnd(12) + ' @hooks/useCart -> ' + (r === null ? 'UNRESOLVED' : r));
}
console.log('TWO PIPELINES (separate alias maps):');
show('app', twoApp);
show('test', twoTest);
console.log('SHARED PIPELINE (one alias map):');
show('app', shared);
show('test', shared);
Output:
TWO PIPELINES (separate alias maps):
app import @hooks/useCart -> /src/hooks/useCart
test import @hooks/useCart -> UNRESOLVED
SHARED PIPELINE (one alias map):
app import @hooks/useCart -> /src/hooks/useCart
test import @hooks/useCart -> /src/hooks/useCart
Under the shared pipeline the colleague's new @hooks alias resolves on both the app and the test side; under two separate maps the test side returns UNRESOLVED - the exact failure the first exercise asks you to diagnose. One map has nowhere to drift to.
Node vs jsdom: choosing where a test runs
The one thing tests do NOT inherit from the app is the runtime itself: the app runs in a browser, a test runs in Node. test.environment bridges that gap. Leave it node for logic that never touches the DOM, and set jsdom for code that reads document, window, or localStorage. A single file can override the project default with a docblock comment on its first line, so one component test never forces a synthetic DOM on the whole suite:
// test.environment picks the globals a test file runs against. 'node' is the
// bare rehearsal room (no document); 'jsdom' is the dressed stage that supplies
// a document and window. A file can override the project default with a docblock.
const DEFAULT_ENV = 'node';
function envFor(docblock) {
const m = docblock.match(/@vitest-environment\s+(\w+)/);
return m ? m[1] : DEFAULT_ENV;
}
function globalsFor(env) {
return env === 'jsdom'
? ['document', 'window', 'localStorage']
: ['process', 'globalThis'];
}
const files = [
['src/lib/price.test.ts', ''],
['src/ui/Cart.test.tsx', '// @vitest-environment jsdom'],
['src/lib/slug.test.ts', ''],
];
for (const [file, doc] of files) {
const env = envFor(doc);
console.log(file.padEnd(24) + ' env=' + env.padEnd(6) + ' has document: ' + globalsFor(env).includes('document'));
}
Output:
src/lib/price.test.ts env=node has document: false
src/ui/Cart.test.tsx env=jsdom has document: true
src/lib/slug.test.ts env=node has document: false
The pure-logic files stay in the light node environment and never pay for a synthetic DOM; only Cart.test.tsx, which opted in with // @vitest-environment jsdom, gets a document. Matching the environment to what a test actually touches keeps the suite fast and keeps each test honest about the world its code runs in.
globals: imported or ambient
With globals: false (the default this project uses) you import the test API explicitly, which keeps a reader able to see where test and expect came from and keeps the global namespace clean:
import { describe, test, expect } from 'vitest'
Setting globals: true makes describe, test, and expect ambient the way Jest does, which shortens a migration but costs the explicit import and needs types: ['vitest/globals'] in tsconfig for the types to resolve. setupFiles run once before each test file and are where global matchers (for instance @testing-library/jest-dom) or shared test doubles are registered.
What the shared pipeline still does not check
Reusing the pipeline also reuses its blind spots, and two are worth naming. First, types are not checked: Vitest strips TypeScript exactly as Vite does, so a green suite says nothing about type correctness and tsc --noEmit remains a separate job. Second, the dev pipeline is not the production build: tests exercise transformed modules, not the Rollup output, so a dev/build asymmetry - a case-sensitive path, an output-only plugin, a tree-shaking difference - is invisible to the runner and only vite build plus vite preview will surface it. Green tells you the logic is sound under the dev pipeline; it is not, by itself, evidence that the project builds or that its types hold.
Real World Example: A Global jsdom Setting That Hides an SSR Crash
A team ships a React app that also renders on the server. Early on, someone set environment: 'jsdom' at the project level because the first tests were component tests, and it was never revisited - so every test file now runs in jsdom whether it needs a DOM or not. A small helper reads a feature flag from localStorage, and it is called both in the browser and inside the SSR render path.
// The suite runs every file in jsdom because the project set environment:'jsdom'
// globally. jsdom supplies localStorage, so a helper that reads it passes. But
// this same helper also runs in an SSR (node) context in production, where
// localStorage does not exist. The test environment is MORE capable than the
// narrowest runtime, so a green suite hides a crash only the real server sees.
function readFlag(globals) {
if (!('localStorage' in globals)) throw new Error('localStorage is not defined');
return globals.localStorage.getItem('flag') === 'on';
}
const jsdomEnv = { localStorage: { getItem: (k) => (k === 'flag' ? 'on' : null) } };
const nodeEnv = {}; // an SSR / node runtime: no DOM globals
function run(label, globals) {
try {
const v = readFlag(globals);
console.log(' ' + label.padEnd(22) + ' -> returned ' + v);
} catch (e) {
console.log(' ' + label.padEnd(22) + ' -> THREW: ' + e.message);
}
}
console.log('SUITE RUNS (environment: jsdom, all files):');
run('test (jsdom)', jsdomEnv);
console.log('PRODUCTION RUNTIME (SSR, node):');
run('prod (node/SSR)', nodeEnv);
Output:
SUITE RUNS (environment: jsdom, all files):
test (jsdom) -> returned true
PRODUCTION RUNTIME (SSR, node):
prod (node/SSR) -> THREW: localStorage is not defined
In the suite the helper returns true and the test is green, because jsdom supplies a localStorage for it to read. The very same function, called during server rendering in production where there is no localStorage, throws localStorage is not defined on the first request. The test and the crash come from one line of code; the only thing that changed is the environment it ran in.
The flaw is not the helper and not a mistaken assertion - the assertion is correct for a browser. The flaw is that the test environment was configured to be MORE capable than the narrowest runtime the code has to survive. Setting jsdom globally handed every file a browser, including files whose code also runs on a bare Node server, so the suite quietly tests them in a world they will not always inhabit. Green here means "works in a browser," which is not the question the SSR path is asking.
This is the one axis the reused pipeline does NOT unify. The resolver, the transforms, and the plugins are genuinely shared with the app, so they cannot drift; but the environment is a test-only setting with no counterpart in the app config, and defaulting it to jsdom widens it past production without anything flagging the gap. The reuse that makes Vitest trustworthy everywhere else is exactly what makes this setting easy to forget - it is the one knob you have to set to match reality yourself.
The durable fix is to default environment to node - the narrowest runtime - and opt the genuinely DOM-bound suites into jsdom per file with // @vitest-environment jsdom. For code that must run in both worlds, the stronger move is to run that suite under BOTH environments, so a missing global fails a test instead of a production request. Match the environment to the narrowest place the code runs, not the most generous, and make the opt-in a loud, per-file decision.
Common Mistakes
- Configuring a separate resolver for tests. If you are copying aliases into a test config, you have re-created the drift Vitest exists to remove; let
resolve.aliasin the Vite config be the only copy.
- Importing
defineConfigfromviteinstead ofvitest/config. Thetestkey is then untyped, so typos in test options are accepted silently; import it fromvitest/config.
- Defaulting the whole project to
environment: 'jsdom'. It hands a browser to files that also run on the server, hiding runtime gaps; default tonodeand opt DOM suites in per file.
- Treating a green suite as proof the build works. Tests run the dev pipeline, not the Rollup output;
vite buildandvite previeware what prove the build.
- Assuming tests type-check your code. Vitest strips types like Vite, so a passing suite says nothing about type correctness; keep
tsc --noEmitas its own step.
- Reaching for Jest out of habit on a Vite project. It works, but you take on a second resolver and transform config to keep in sync by hand; Vitest removes that duplicate by design.
- Forgetting
setupFilesfor DOM matchers. Without registering something like@testing-library/jest-dom, matchers such astoBeInTheDocumentare undefined; register them once in a setup file.
- Enabling
globals: trueand expecting types to just work. You also needtypes: ['vitest/globals']intsconfig, or the ambienttestandexpectstay untyped.
- Widening a whole suite for one component test. Add a
// @vitest-environment jsdomdocblock to that single file instead of paying for a synthetic DOM everywhere.
Best Practices
- Keep one source of truth. Declare aliases, transforms, and plugins once in the Vite config and let the
testblock inherit them; never maintain a parallel test resolver.
- Default the environment to
node. Start every suite in the narrowest runtime and opt individual DOM suites intojsdom, so the environment matches where the code actually runs.
- Test isomorphic code in both worlds. For a helper that runs in the browser and on the server, run its suite under
nodeandjsdomso a missing global fails a test, not a request.
- Import
defineConfigfromvitest/config. It types thetestkey and catches option typos at author time instead of letting them pass silently.
- Keep
tsc --noEmitin CI beside the suite. The runner strips types, so type checking has to be its own job to close that blind spot.
- Verify the build, not just the tests. Run
vite buildandvite previewin CI so dev/build asymmetries surface before users meet them.
- Prefer explicit imports over
globals: true. Importingtestandexpectkeeps their origin visible and the namespace clean; reserve ambient globals for easing a Jest migration.
- Put shared setup in
setupFiles. Register DOM matchers and global test doubles once so every file starts from the same baseline instead of repeating boilerplate.
Practice Exercises
- Diagnose the alias. A colleague adds
@hookstoresolve.alias; the app builds but the test suite cannot resolve@hooks/.... State what that tells you about which runner the project uses, and give the fix for both the Vitest case and the separate-runner case.
- Pick the environment. For each file - a currency-formatting utility, a React component that reads
document, and an SSR data loader that runs only on the server - say whether it should run undernodeorjsdomand why, and show the docblock you would add if it differs from anodedefault.
- Explain the green suite. A teammate says "the tests pass, so we can deploy." Name two specific things a passing Vitest run does not verify, and the exact command or job that verifies each.
- Close the SSR gap. Given the
readFlaghelper from the Real World Example that throws under a bare Node runtime, describe two changes - one to the test configuration, one to the helper - that would make the suite catch the missinglocalStoragebefore production does.