The Analogy: The Engine Test Cell
An engine test cell is a sealed room where a new engine runs bolted to a dynamometer instead of installed in a car, and it is the cleanest picture of what mocking is for: the shop services standing in for the vehicle are the mocks. A spy (vi.fn or vi.spyOn) is a clamp-on sensor on a real fuel line - it records every reading, flow and pressure and rpm, without changing how the engine runs, and it unclips afterward. A mock (vi.mock) is the heavier substitution: the fuel cart that replaces the car's entire fuel system for the duration of the run, so the engine draws from a supply you control completely rather than the one it will actually ship with.
You put the engine on the stand precisely to replace the things you cannot or must not reproduce in the room - the open road, a thousand miles of wear, a cold February morning - with dials you set by hand. What you never replace is the engine itself: swap in a dummy block and the cell measures nothing, because the thing under test has left the room. And you do not bench a plain bolt you could simply torque and check directly; a stand-in for something cheap and honest only adds one more part that can lie to you.
The instrument panel counts which gauges lit during a run, and that count is a floor, not a verdict - proof the run touched those systems, nothing more. You can spin the engine, light every gauge on the board, and still have recorded nothing about whether the torque curve sits inside spec, because lighting a gauge and reading it against a limit are two different acts. A board that is all green tells you the wiring works; it does not tell you the engine is good.
The failure is signing the engine off for the car because the cell run was clean - when the cell fed it filtered lab fuel, held the room at twenty degrees, and never loaded it the way a mountain grade will. A stand that stands in for too much certifies the stand-ins, not the engine, and the first cold, dirty, fully loaded morning finds every question the controlled room was arranged never to ask. Worse still is the cart plumbed years ago for last season's fuel: the run is flawless against a supply the car no longer uses, and the number on the board is honest about a fiction.
Syntax or Core Structure
Two instruments cover most mocking. vi.spyOn wraps a single real method so you can observe or briefly replace it and then restore it; vi.mock replaces a whole module for the file. Reach for the smaller one first - it leaves more real code running under the test:
import { vi, test, expect } from 'vitest'
test('warns once when disk is low', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
checkDisk({ freePercent: 3 })
expect(warn).toHaveBeenCalledTimes(1)
warn.mockRestore()
})
// replace an entire module - hoisted above the imports
vi.mock('@/lib/analytics', () => ({ track: vi.fn() }))
A spy is just a function that records how it was called and, optionally, stands in for the real one. A small hand-built version - record the arguments, keep the original behaviour, hand back a restore - prints exactly what the recorder captured:
// A minimal stand-in for vi.fn(): a callable that records how it was used.
function fn(impl) {
const f = function (...args) {
f.mock.calls.push(args);
return impl ? impl(...args) : undefined;
};
f.mock = { calls: [] };
return f;
}
// A minimal stand-in for vi.spyOn: wrap one method, record every call, keep
// the real behaviour, and hand back a restore() that puts the original back.
function spyOn(obj, key) {
const original = obj[key];
const s = fn((...args) => original.apply(obj, args));
obj[key] = s;
s.restore = () => { obj[key] = original; };
return s;
}
// A collaborator we want to observe without changing what it does.
const logger = {
lines: [],
warn(msg) { this.lines.push('WARN ' + msg); },
};
const warn = spyOn(logger, 'warn');
logger.warn('low disk');
logger.warn('low disk');
console.log('warn called ' + warn.mock.calls.length + ' times');
console.log('first call args: ' + JSON.stringify(warn.mock.calls[0]));
console.log('real behaviour kept: ' + JSON.stringify(logger.lines));
warn.restore();
logger.warn('after restore');
console.log('after restore, spy still ' + warn.mock.calls.length + ' calls');
console.log('logger saw: ' + JSON.stringify(logger.lines));
Output:
warn called 2 times
first call args: ["low disk"]
real behaviour kept: ["WARN low disk","WARN low disk"]
after restore, spy still 2 calls
logger saw: ["WARN low disk","WARN low disk","WARN after restore"]
The spy counts every call and keeps the arguments, so an assertion can check not just what a function returned but how a collaborator was used; once restored, the real method is back and the recorder stops growing. That distinction - observe without disturbing, then put it back - is the whole reason to prefer a spy over replacing the module wholesale.
Technical Depth: Spies, Isolation, Timers, and the Coverage Gate
Spies versus module mocks
A spy and a module mock answer different questions. A spy is a probe you attach to a collaborator you already hold - assert how it was called, optionally fix what it returns. A module mock rewrites what an import resolves to for the entire file, and because Vitest hoists vi.mock above the imports, its factory runs before any module-level variable exists - the source of the "cannot access X before initialization" error that surprises everyone once.
| Tool | What it does | Reach for it when |
|---|---|---|
vi.fn() | A blank spy that records calls, configurable return | Asserting how a passed-in collaborator was called |
vi.spyOn(obj, key) | Wraps one real method, records, restorable | Observing or briefly replacing a single method |
vi.mock('mod') | Replaces a whole module for the file (hoisted) | The module does I/O or is not yours to run |
mockReturnValue(v) | Fixes the value the spy returns | The code branches on the collaborator's result |
mockResolvedValue(v) | Fixes a resolved promise | The collaborator is async |
Configuring a return value and then asserting on the recorded call is the core loop:
function fn() {
const f = function (...args) {
f.mock.calls.push(args);
return f._impl ? f._impl(...args) : f._return;
};
f.mock = { calls: [] };
f.mockReturnValue = (v) => { f._return = v; return f; };
f.mockImplementation = (i) => { f._impl = i; return f; };
return f;
}
// Configure a mock to stand in for a real dependency's return value.
const getRate = fn().mockReturnValue(1.1);
// The unit under test receives the collaborator as an argument.
function priceWithTax(rate, cents) {
return Math.round(cents * rate());
}
const out = priceWithTax(getRate, 2000);
console.log('priceWithTax(2000) -> ' + out);
console.log('getRate called ' + getRate.mock.calls.length + ' time(s)');
// Assert HOW a collaborator was called, not only what came back.
const send = fn();
function notify(sender, user) {
sender('email', user + '@example.com');
}
notify(send, 'ada');
const call = send.mock.calls[0];
console.log('send called with channel=' + call[0] + ' to=' + call[1]);
console.log('called exactly once: ' + (send.mock.calls.length === 1));
Output:
priceWithTax(2000) -> 2200
getRate called 1 time(s)
send called with channel=email to=ada@example.com
called exactly once: true
The mock returns the rate the test dictated, so priceWithTax is exercised against a value you control, and the recorded call proves notify reached the sender exactly once with the arguments you expected. Nothing here touched a network or a real rate service.
Resetting state between tests
A spy accumulates calls for as long as it lives. Share one across tests without clearing it and the call count from an earlier test bleeds into a later one, so the suite passes or fails by running order - the mocking version of a fixture you forgot to rebuild:
function fn() {
const f = function (...a) { f.mock.calls.push(a); };
f.mock = { calls: [] };
f.mockClear = () => { f.mock.calls = []; };
return f;
}
const analytics = { track: fn() };
// A registry of every spy, like vitest's clearMocks running between tests.
const spies = [analytics.track];
function clearAllMocks() { spies.forEach((s) => s.mockClear()); }
function testA() {
analytics.track('signup');
console.log(' A: track calls seen = ' + analytics.track.mock.calls.length);
}
function testB() {
// B means to assert the event fired exactly once during B.
analytics.track('purchase');
console.log(' B: track calls seen = ' + analytics.track.mock.calls.length);
}
console.log('without reset between tests:');
testA();
testB();
analytics.track.mockClear(); // reset the demo before the second run
console.log('with clearAllMocks() between tests:');
testA();
clearAllMocks();
testB();
Output:
without reset between tests:
A: track calls seen = 1
B: track calls seen = 2
with clearAllMocks() between tests:
A: track calls seen = 1
B: track calls seen = 1
Without a reset, test B sees two calls - its own plus A's - and any assertion of "called once" is now hostage to order. Setting clearMocks: true (or restoreMocks: true, which also un-wraps spies) in the config runs that reset before every test automatically, so isolation is not something each test has to remember.
Faking time
A test that polls or debounces should not spend real seconds waiting. vi.useFakeTimers() swaps the global clock for one the test drives, so a three-second poll finishes the instant you advance the clock by hand:
import { vi, test, expect, beforeEach, afterEach } from 'vitest'
import { pollUntilReady } from '@/lib/poll'
beforeEach(() => { vi.useFakeTimers() })
afterEach(() => { vi.useRealTimers() })
test('polls three times then resolves', async () => {
const check = vi.fn()
.mockResolvedValueOnce({ ready: false })
.mockResolvedValueOnce({ ready: false })
.mockResolvedValueOnce({ ready: true })
const done = pollUntilReady(check, { everyMs: 1000 })
// No real second passes; we advance the clock by hand.
await vi.advanceTimersByTimeAsync(3000)
await expect(done).resolves.toBe(true)
expect(check).toHaveBeenCalledTimes(3)
})
advanceTimersByTimeAsync moves the fake clock forward AND flushes the promise microtasks each timer schedules, which is why the await on the result resolves; the synchronous advanceTimersByTime would move the clock but never let the awaited work run. The one rule that matters: pair every useFakeTimers with useRealTimers in afterEach, or the faked clock leaks into the next test file and something unrelated hangs forever.
Coverage as a floor, and the CI gate
Coverage counts which lines a run executed - a floor under your testing, never a verdict on it. Vitest reads it from V8, which needs one dependency:
npm install -D @vitest/coverage-v8
npx vitest run --coverage
Turn it into a gate in the config: reset mocks between tests so isolation is automatic, and set thresholds so the suite fails when coverage drops below the floor you have already reached:
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
restoreMocks: true, // un-wrap spies and clear calls before every test
coverage: {
provider: 'v8',
thresholds: { lines: 80, functions: 80, branches: 75 },
},
},
})
The thresholds are a ratchet, not a target: set them where you are, raise them as you add tests, and a careless deletion of tests now breaks the build instead of sliding by. CI runs the same gate on every push, and the order is deliberate - cheap checks first, the build last, so a lint error fails in seconds rather than after a full compile:
npm ci # exact, reproducible install from the lockfile
npm run lint
npm run typecheck
npm run test:run # vitest run --coverage, non-watch
npm run build # the check a green test suite does not give you
npm ci installs the exact tree the lockfile pins and fails if package.json and the lockfile disagree, so the machine builds what you committed rather than whatever npm install resolves today. The build step earns its place at the end: a suite can be all green while vite build still fails on a type error or a bad import, because running the tests and producing a production bundle are two different questions.
Real World Example: A Green Suite That Ships "confirmed undefined"
A suite can be green, fast, and fully covered and still ship a bug the first real request would have caught. Here is a checkout that charges a payment gateway. The suite mocks the gateway - sensibly, since tests must not hit a real payment API - and the mock was written months ago. Watch what the same code does against the mock, against the real gateway, and then look at why they differ:
// The real payment gateway as it behaves in production TODAY. Its success
// shape changed last quarter: the charge id moved from a top-level `chargeId`
// to a nested `receipt.id`. It is async.
const realGateway = {
async charge(cents) {
if (cents > 100000) return { ok: false };
return { ok: true, receipt: { id: 'ch_' + cents } };
},
};
// The mock the suite installs in place of the gateway. It was written against
// the OLD success shape (top-level chargeId) and was never updated.
const mockGateway = {
async charge(cents) {
if (cents > 100000) return { ok: false };
return { ok: true, chargeId: 'ch_' + cents };
},
};
// The unit under test, instrumented so we can count which lines ran.
function makeCheckout(hit) {
return async function checkout(gateway, cents) {
hit.add('L1'); const res = await gateway.charge(cents);
hit.add('L2'); if (!res.ok) { hit.add('L3'); return 'failed'; }
hit.add('L4'); return 'confirmed ' + res.chargeId;
};
}
const LINES = ['L1', 'L2', 'L3', 'L4'];
async function runSuite() {
const hit = new Set();
const checkout = makeCheckout(hit);
const cases = [
['confirms a charge', 1200, 'confirmed ch_1200'],
['declines over the limit', 200000, 'failed'],
];
console.log('suite (checkout against the MOCK):');
for (const [name, cents, expected] of cases) {
const got = await checkout(mockGateway, cents);
console.log(' ' + (got === expected ? 'PASS' : 'FAIL') + ' ' + name + ' -> ' + got);
}
const pct = Math.round((hit.size / LINES.length) * 100);
console.log(' coverage: lines ' + hit.size + '/' + LINES.length + ' (' + pct + ' percent of checkout)');
}
async function runReal() {
const checkout = makeCheckout(new Set());
console.log('the SAME checkout against the REAL gateway:');
console.log(' charge 1200 -> ' + (await checkout(realGateway, 1200)));
console.log(' charge 5000 -> ' + (await checkout(realGateway, 5000)));
}
async function contractCheck() {
const mockRes = await mockGateway.charge(1200);
const realRes = await realGateway.charge(1200);
console.log('contract check (keys the code reads vs keys reality returns):');
console.log(' mock success keys: ' + Object.keys(mockRes).join(', '));
console.log(' real success keys: ' + Object.keys(realRes).join(', '));
}
(async () => {
await runSuite();
console.log('');
await runReal();
console.log('');
await contractCheck();
})();
Output:
suite (checkout against the MOCK):
PASS confirms a charge -> confirmed ch_1200
PASS declines over the limit -> failed
coverage: lines 4/4 (100 percent of checkout)
the SAME checkout against the REAL gateway:
charge 1200 -> confirmed undefined
charge 5000 -> confirmed undefined
contract check (keys the code reads vs keys reality returns):
mock success keys: ok, chargeId
real success keys: ok, receipt
The suite runs checkout against mockGateway and both cases pass; the coverage line reports every line of checkout executed - a perfect 100 percent. By every signal a CI dashboard shows, this code is done. Then the same checkout runs against realGateway, the gateway as it actually behaves today, and returns confirmed undefined for a charge that plainly succeeded.
The contract check names the cause. checkout reads res.chargeId, and the mock hands back exactly that key, so mock and code agree and the test is green. But the real gateway moved that value to receipt.id last quarter; its success object has no chargeId at all, so res.chargeId is undefined and the customer sees a confirmation with no charge id. The mock and the code share one stale assumption about the gateway's shape, and they validate each other while both disagree with reality.
Coverage cannot catch this, and it is worth being precise about why. The metric measures which lines of checkout ran, not whether the values flowing through them were shaped like production's. Every line ran - against a fixture that lies - so the number is 100 percent and completely beside the point. A higher threshold would not have helped; the gap is not an untested line, it is an untested assumption.
The design flaw is that nothing in the suite ever compares the mock to the thing it stands in for. A mock is a copy of a contract, and copies drift; the moment the real gateway changed its response shape, the mock became a fixture for an API that no longer exists, and the suite started certifying fiction. The fix is not more unit tests - it is a contract test: one check that hits the real gateway (or its recorded schema) and asserts the keys checkout depends on are actually present, so the day chargeId becomes receipt.id a test goes red instead of a customer getting confirmed undefined.
Common Mistakes
- Mocking your own pure functions. A function that only transforms its inputs needs no stand-in - call it and assert what it returns. A mock there tests the mock, not the code, and freezes whatever behaviour you assumed into the suite.
- Mocking the module you are testing. Replace a collaborator, never the unit under test. Once
vi.mockpoints at the file whose behaviour you are asserting, the test measures the fixture and the real code can rot untouched behind it. - Over-mocking until the test proves nothing. Every mock is a boundary you have stopped exercising. Mock the network and the clock; do not mock the internal helpers the function calls, or a green run tells you only that your mocks return what you told them to.
- Leaving fake timers installed.
vi.useFakeTimers()with no matchingvi.useRealTimers()inafterEachleaks a frozen clock into the next file, where an unrelated test that awaits a real timeout hangs until the runner kills it. - Not resetting spies between tests. A shared spy keeps its call log, so
toHaveBeenCalledTimes(1)passes or fails by test order. SetrestoreMocks(orclearMocks) in the config instead of trusting every test to clean up after itself. - Treating the coverage number as the goal. Lines executed is a floor, not a grade. Code can be 100 percent covered by tests that assert nothing meaningful; chasing the percentage produces tests written to touch lines rather than to catch bugs.
- Letting a mock drift from the real contract. A mock written against last quarter's response shape stays green forever while production returns something else. Nothing re-checks the mock against reality unless you add a contract or integration test that does.
- Skipping the build step in CI. A passing test suite does not prove the app compiles or bundles.
vite buildcatches type errors and bad imports that unit tests, running transformed source, never see - so run it in the pipeline. - Using
npm installin CI instead ofnpm ci.npm installmay quietly rewrite the lockfile and resolve different versions than you tested;npm ciinstalls the exact pinned tree and fails on a mismatch, so the machine builds what you committed.
Best Practices
- Reach for
spyOnbeforevi.mock. A spy leaves the rest of the module running and restores cleanly; mocking the whole module replaces far more than you usually mean to. Use the smallest tool that isolates the one thing you cannot run. - Inject collaborators instead of importing them. A function that takes its gateway, clock, or logger as an argument is tested by passing a fake - no hoisting, no module rewriting. Hard-to-mock code is usually code that reached out for its dependencies instead of accepting them.
- Mock only real boundaries. The network, the filesystem, the clock, third-party services - the things you cannot or must not run in a unit test. Everything inside your own module should run for real, or the test stops proving your code works.
- Reset mocks in config, not by hand. Set
restoreMocks: true(orclearMocks) once so every test starts clean automatically. Isolation you have to remember in each test is isolation you will eventually forget. - Always pair fake timers with a restore. Call
vi.useRealTimers()inafterEachevery time you fake the clock, so a frozen clock never survives into the next file. Treat setup and teardown as a single unit you write together. - Treat coverage as a floor and ratchet it. Set the threshold at today's number, raise it as you add tests, and let CI fail a drop - but never mistake the percentage for proof the assertions are meaningful.
- Verify every mock against the real contract. Back each mocked boundary with a contract or integration test that touches the real shape, so a mock cannot quietly drift from the thing it imitates and ship "confirmed undefined".
- Make CI run the whole gate on
npm ci. Install withnpm ci, then lint, typecheck, run the tests with coverage, build, and scan for committed secrets - cheap checks first, the build last - so nothing reaches production that the pipeline has not actually exercised.
Practice Exercises
- Remove the over-mock. Take a test that mocks a function's own internal helpers and delete those mocks so the helpers run for real. Watch whether the test still passes, then decide which - if any - of the original mocks was testing anything but itself.
- Catch the drift. Using the checkout example, write the missing contract test: one that calls the real gateway's
chargeand asserts the success object carries the keycheckoutreads. Confirm it goes red against the old mock's shape and green once code and contract agree. - Harden the pipeline. Write a CI script that runs
npm ci, lint, typecheck,vitest run --coverage, andvite buildin that order, and add a coverage threshold set to your current number. Break one step on purpose and confirm the pipeline fails at the cheapest check, not the build. - Justify each mock. Take a real test file and, for every mock in it, write one sentence naming the real boundary it stands in for. Delete any mock whose sentence describes your own code rather than a network, clock, filesystem, or third-party edge.