The Analogy: The Analytical Lab Bench
A testing suite is an analytical lab, and each test is a single assay: you take a known sample, apply one reagent, and read one instrument against a value you wrote down in advance. A describe block is the protocol sheet that groups every assay for one substance under a heading; a test is a single line on that sheet - "add reagent, expect the solution to turn blue" - and expect(x).toBe(y) is the moment you hold the reading up against the expected value and record pass or fail. An assay with no expected value written down measures nothing; it is the test that asserts nothing and passes because it never checked.
The reading is only as honest as the instrument you choose, and the bench keeps several that look interchangeable but are not. toBe is reading whether two labels name the very same physical vial (reference identity); toEqual is confirming that two different vials hold the same contents (structural equality). Reach for the identity instrument when you meant the contents one and you get a false failure: two vials mixed from the same recipe are not the same vial, so toBe reports "different" about samples that are, for every purpose that matters, equal.
Isolation is the discipline that makes the whole bench trustworthy. Before every assay the wash station hands you freshly cleaned glassware (beforeEach), and after it the used glassware is taken away to be washed (afterEach); the point is that no assay ever inherits another's residue, so the order you happen to run them in cannot change a single reading. A one-time setup for the whole session - warming up the shared spectrometer - is beforeAll, and shutting it down at the end is afterAll.
The failure mode is the bench that skips the wash and lets two assays share one unwashed tube. A later assay can then read "pass" only because residue from the earlier one is still sitting in the glass; wash the tube properly - or simply run that assay first, before anything has been added - and the identical reading flips to fail. The green result was never measuring the sample in front of it; it was measuring what the previous assay left behind, and a result that depends on running order is not evidence about the sample at all.
Syntax or Core Structure
A Vitest test file imports the API explicitly, groups related cases under describe, and states each expectation with expect and a matcher. The failure path deserves at least as much attention as the happy path - it is where the bugs that reach users actually live:
import { describe, test, expect } from 'vitest'
import { formatPrice } from '@/lib/format'
describe('formatPrice', () => {
test('renders whole amounts without decimals', () => {
expect(formatPrice(1200)).toBe('12')
})
test('rejects negative input', () => {
expect(() => formatPrice(-1)).toThrow()
})
})
The matcher is the instrument, and picking the wrong one is the most common way to get a misleading reading. A small stand-in for expect - identity for toBe, deep structural equality for toEqual, "did it throw" for toThrow - prints exactly what a real runner prints, one PASS or FAIL per assertion:
function deepEqual(a, b) {
if (Object.is(a, b)) return true;
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
const ak = Object.keys(a), bk = Object.keys(b);
if (ak.length !== bk.length) return false;
return ak.every((k) => deepEqual(a[k], b[k]));
}
function expect(received) {
return {
toBe(expected) { return Object.is(received, expected); },
toEqual(expected) { return deepEqual(received, expected); },
toThrow() { try { received(); return false; } catch (e) { return true; } },
};
}
function check(name, pass) {
console.log((pass ? 'PASS' : 'FAIL') + ' ' + name);
}
check('formatPrice(1200) toBe "12"', expect('12').toBe('12'));
check('parseTags toEqual [sale,new]', expect(['sale', 'new']).toEqual(['sale', 'new']));
check('divide(1,0) toThrow', expect(() => { throw new Error('x'); }).toThrow());
check('two equal objects toBe (identity)', expect({ id: 7 }).toBe({ id: 7 }));
Output:
PASS formatPrice(1200) toBe "12"
PASS parseTags toEqual [sale,new]
PASS divide(1,0) toThrow
FAIL two equal objects toBe (identity)
The first three assertions pass; the fourth FAILS on purpose. { id: 7 } and { id: 7 } are two separately built objects, so the identity check toBe correctly reports them as different references even though their contents match. That last line is the whole trap of matcher choice in one row, and the Technical Depth section takes it apart.
Technical Depth: The Anatomy of a Run - Matchers, Lifecycle, and Isolation
Matchers: identity, equality, and error paths
Matchers fall into a few families, and the pair that trips people up is toBe versus toEqual. toBe uses Object.is, which is reference identity for objects and value equality for primitives; toEqual walks the structure and compares contents. For a number or string the two agree; for an object or array they part ways completely.
| Matcher | Asks | Use for |
|---|---|---|
toBe | Same reference? (Object.is) | Primitives, "is the exact same object" |
toEqual | Same contents? (deep) | Objects, arrays, most value assertions |
toThrow | Did the function throw? | Error paths, guard clauses |
toContain | Is the item a member? | Arrays, substrings |
.not | Inverts any matcher | Asserting absence |
The same two structurally-equal objects, read once with each instrument, show the split directly - and confirm that on primitives the two agree:
function deepEqual(a, b) {
if (Object.is(a, b)) return true;
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;
const ak = Object.keys(a), bk = Object.keys(b);
if (ak.length !== bk.length) return false;
return ak.every((k) => deepEqual(a[k], b[k]));
}
const left = { id: 7, tags: ['sale', 'new'] };
const right = { id: 7, tags: ['sale', 'new'] };
function line(matcher, pass) {
console.log(' ' + matcher.padEnd(24) + ' -> ' + (pass ? 'PASS' : 'FAIL'));
}
console.log('two structurally-equal objects:');
line('toBe (identity)', Object.is(left, right));
line('toEqual (structural)', deepEqual(left, right));
console.log('a value against itself:');
line('toBe (same reference)', Object.is(left, left));
console.log('primitives:');
line('toBe(12) on 12', Object.is(12, 12));
line('toEqual(12) on 12', deepEqual(12, 12));
Output:
two structurally-equal objects:
toBe (identity) -> FAIL
toEqual (structural) -> PASS
a value against itself:
toBe (same reference) -> PASS
primitives:
toBe(12) on 12 -> PASS
toEqual(12) on 12 -> PASS
The object rows disagree - toBe FAILS because left and right are distinct references, toEqual PASSES because their contents match - while every primitive row agrees. The rule that falls out: reach for toEqual on objects and arrays, and reserve toBe for primitives or for the rare "must be the very same instance" assertion.
Lifecycle hooks and per-test isolation
The lifecycle hooks decide what state each test starts from. beforeEach and afterEach run around every test in scope; beforeAll and afterAll run once for the file. Rebuilding the fixture in beforeEach is what makes a suite order-independent: each test gets its own clean instance, so nothing one test does can leak into the next.
const log = [];
function record(s) { log.push(s); }
let cart; // the per-test fixture
function beforeAll() { record('beforeAll: open suite'); }
function afterAll() { record('afterAll: close suite'); }
function beforeEach() { cart = []; record(' beforeEach: fresh cart []'); }
function afterEach() { record(' afterEach: discard cart'); }
function runTest(name, body) {
beforeEach();
body();
record(' test: ' + name + ' -> cart has ' + cart.length);
afterEach();
}
beforeAll();
runTest('adds one item', () => { cart.push('widget'); });
runTest('starts empty', () => { /* touches nothing */ });
afterAll();
console.log(log.join('\n'));
Output:
beforeAll: open suite
beforeEach: fresh cart []
test: adds one item -> cart has 1
afterEach: discard cart
beforeEach: fresh cart []
test: starts empty -> cart has 0
afterEach: discard cart
afterAll: close suite
The second test reports cart has 0 even though the first pushed an item, because beforeEach rebuilt cart as a fresh [] between them. That single reset is the difference between a suite you can run in any order and one whose results depend on history - the exact fragility the Real World Example builds out.
Async assertions
Asynchronous code needs the assertion itself to be awaited, or the test can finish before the promise settles and pass without ever checking. Vitest exposes resolves and rejects for this, and both must be preceded by await:
import { test, expect } from 'vitest'
import { loadUser } from '@/lib/api'
test('resolves to a user', async () => {
await expect(loadUser(7)).resolves.toEqual({ id: 7, name: 'Ada' })
})
test('rejects an unknown id', async () => {
await expect(loadUser(0)).rejects.toThrow('not found')
})
Drop the await and the test body returns before the promise rejects; the assertion never runs and the test is a false green. This is the async twin of the shared-state bug: in both, a test passes for a reason unrelated to the behaviour it claims to verify.
Selecting and filtering what runs
During development you rarely run everything. Vitest gives per-test switches - test.only narrows the run to marked tests, test.skip parks one, test.todo records an intention - and the command line filters by file path or test name:
vitest # watch mode: re-runs only affected tests on save
vitest run # single pass, exits with a status code (use in CI)
vitest run src/lib # limit to a path
vitest run -t "rejects" # only tests whose name matches
only and skip are development conveniences, not things to commit: a test.only left in a file quietly shrinks the whole suite to one test, which the next section and the mistakes list both return to.
Real World Example: A Suite That Passes Only in Order
A checkout suite shares one module-level fixture across its tests and never resets it. The first test adds an item; a later test asserts the total reflects one item. In the file's declaration order everything is green, so it ships. The script below models the suite three ways - in declaration order, reordered, and with the later test run alone the way test.only would run it - using one shared object that is reset only when the "module" reloads, never between tests:
// Two tests share ONE module-level object and never reset it between tests.
// In declaration order, B passes only because A ran first and left an item
// behind. Reorder the tests, or run B alone, and B fails - the green result
// was reading A's residue, not B's own setup.
const shared = { items: [] }; // module-level fixture, never reset per test
const tests = {
'A: adds an item': () => {
shared.items.push('widget');
return shared.items.length === 1;
},
'B: total reflects one item': () => {
// BUG: assumes A already ran and left exactly one item in the shared fixture.
return shared.items.length === 1;
},
};
function runSuite(label, order) {
shared.items = []; // one fresh module load per run; tests do NOT reset between cases
console.log(label);
for (const name of order) {
const pass = tests[name]();
console.log(' ' + (pass ? 'PASS' : 'FAIL') + ' ' + name);
}
}
runSuite('declaration order (A then B):', ['A: adds an item', 'B: total reflects one item']);
runSuite('reordered (B then A):', ['B: total reflects one item', 'A: adds an item']);
runSuite('B alone (.only on B):', ['B: total reflects one item']);
Output:
declaration order (A then B):
PASS A: adds an item
PASS B: total reflects one item
reordered (B then A):
FAIL B: total reflects one item
PASS A: adds an item
B alone (.only on B):
FAIL B: total reflects one item
In declaration order both tests pass: A pushes a widget, and B then sees items.length === 1 and reads green. But B never set that item up - it inherited it from A. Reorder the two so B runs first and B FAILS, then A passes; isolate B the way test.only would and B FAILS outright. The behaviour B claims to check never changed; only what ran before it did.
This is exactly the unwashed-tube failure from the analogy. B is a real, plausible assertion - "the total reflects one item" - and in the one ordering the author happened to run it, it is even true. The suite is green on the developer's machine and green in the pull request, because CI also runs the file top to bottom. The bug hides until someone adds a test.only while debugging, or the runner parallelises, or a new test is inserted above B, and then a test that "was passing" starts failing with no change to the code it tests.
The flaw is not B's assertion; it is that the suite carries state between tests through a shared, module-level fixture that no hook resets. Test independence is a property you have to build, and the tool cannot infer it: Vitest will happily run stateful tests in whatever order is fastest. The fix is one hook - rebuild the fixture in beforeEach (shared.items = [] before every test) so each test constructs the exact state it asserts on - which turns "passes because of order" into "passes because the behaviour is correct." Any suite whose result changes when you shuffle the tests is reporting on execution order, not on the code.
Common Mistakes
- Setting
environment: 'jsdom'for the whole project. Every pure-logic file then pays for a synthetic DOM it never touches; default tonodeand opt individual files in with a// @vitest-environment jsdomdocblock.
- Testing only the happy path. A suite that never asserts on the failure path tells you the code works when nothing goes wrong - the case you were least worried about; assert on thrown errors and rejected promises too.
- Using
toBeon objects or arrays.toBeis reference identity, so it fails on two structurally-equal objects; usetoEqualfor contents and reservetoBefor primitives or same-instance checks.
- Sharing mutable state across tests. A fixture that is not rebuilt between tests makes results depend on order, so a green suite can hide a broken test; reset state in
beforeEach.
- Running plain
vitestin CI. Watch mode never exits, so the pipeline step hangs until the job times out; CI must callvitest run.
- Forgetting
awaiton async assertions.expect(promise).rejects.toThrow()withoutawaitlets the test finish before the assertion runs, passing without checking anything; always awaitresolves/rejects.
- Committing a
test.only. It silently narrows the whole suite to one test, so CI goes green while covering almost nothing; keeponlyfor local runs and let a lint rule catch stragglers.
- Asserting on implementation details. Checking internal state or private fields breaks on every refactor while proving nothing about what a user sees; assert on rendered output and observable behaviour.
- Letting CI write snapshots. A snapshot created during a CI run asserts that the current behaviour is the current behaviour; make the pipeline fail on missing snapshots instead of writing them.
Best Practices
- Default the environment to
node. Start every suite in the fastest runtime and scopejsdomto the files that genuinely render DOM, with a per-file docblock.
- Assert the failure path. Cover thrown errors, rejected promises, and guard clauses, not just the case where every input is valid.
- Match the matcher to intent. Use
toEqualfor object and array contents,toBefor primitives and identity,toThrowfor error paths - the wrong instrument gives a false reading.
- Rebuild fixtures in
beforeEach. Give every test its own clean state so the suite is order-independent and a shuffled run cannot change a result.
- Use
vitest runin CI and watch mode locally. The single pass exits with a status code; watch stays resident and re-runs only what your change affects.
- Query by role and label in component tests. A control with no accessible name to query by is telling you about an accessibility gap, not just a test inconvenience.
- Always
awaitasync assertions. Precederesolvesandrejectswithawaitso the assertion actually runs before the test ends.
- Keep setup files small and visible. Put only broad, cross-cutting arrangements in
setupFiles; hidden global state makes a failure's cause live in a file the reader never opened.
Practice Exercises
- Break the order dependence. Given the checkout suite from the Real World Example - where test
Bpasses only afterAruns - name the hook you would add and the one line inside it that makesBpass or fail regardless of order.
- Pick the matcher. For three assertions -
formatPrice(1200)equals'12',parseTags('a,b')equals['a', 'b'], andparse('')throws - state which oftoBe,toEqual, ortoThrowyou would use for each and why the other two are wrong for it.
- Unhang the pipeline. A CI test step runs, prints nothing, and is killed at the job timeout with no test results. State the single most likely cause and the exact command that fixes it.
- Scope the environment. A suite of forty files is set to
environment: 'jsdom'globally, and thirty-six of them test pure functions. Give the config change that sets the right default and the one-line docblock you add to each of the four DOM files.