JS-210 · Lesson 7 of 12 · 26 min
Mocks and test doubles
▶ Video coming soon A video version of this lesson is on the way.
On Tuesday, November 9, Mira tries to test the office dashboard's "starting soon" panel, which lists the shifts that begin within the next two hours. Her first test passes at 10 in the morning and fails at 3 in the afternoon, because the panel uses the real clock. Her second test needs Theo's server running, and fails on the train home because there is no network. "Your tests are talking to the outside world," Gareth says. "The clock, the network, the browser's storage. A unit test should control everything its unit touches. Today we replace the outside world with stand-ins."
Those stand-ins are called test doubles, by analogy with a stunt double who stands in for an actor. This lesson explains the kinds of test double, how to design code so that doubles can be swapped in, how Vitest and Jest create them with functions such as vi.fn and vi.useFakeTimers, and when replacing real code makes a test worse rather than better.
Why replace real dependencies?
A unit rarely works alone. The starting-soon panel reads the current time, asks Theo's API for today's shifts and remembers which shifts Lucy has dismissed in localStorage. Each of these dependencies makes a test harder.
- The clock changes, so a test that depends on the time passes or fails depending on when it runs.
- The network is slow, can fail and may not be there at all. A test that calls a real server also depends on the data in that server today.
- Storage and other shared state carry values from one test to the next, so tests stop being independent.
- Side effects such as sending an email to a volunteer or printing a kitchen ticket must not happen during a test.
A test double replaces a dependency with something the test controls completely. With a fake clock, the test decides what time it is. With a stub in place of the API, the test decides what the server returns, including errors that are hard to cause on purpose. With a spy, the test can check that the code asked for the right thing, such as sending a reminder exactly once.
Kinds of test double
The names below come from Gerard Meszaros's book xUnit Test Patterns, and many teams use them loosely. What matters is the idea behind each: what the double does and what the test checks with it.
| Kind | What it is | Food Hub example |
|---|---|---|
| Dummy | A value passed only to fill a parameter; never used | An empty options object the code ignores in this case |
| Stub | Returns fixed answers to calls | A getShifts function that always returns the same three shifts |
| Spy | Records how it was called, and may pass the call on | A wrapper around sendReminder that counts calls and their arguments |
| Mock | A double with expectations about how it will be called, checked by the test | A printer that must receive exactly one ticket with the order number |
| Fake | A working, simplified implementation | An in-memory storage object that behaves like localStorage |
Designing for doubles: dependency injection
A double can only replace a dependency if the code lets it. The simplest way is dependency injection: instead of reaching out for the clock or the API itself, a function receives them as parameters, usually with the real ones as defaults. The code works the same in production, and a test can pass in doubles.
// Hard to test: the function reaches for the real clock itself.
function startingSoonHard(shifts) {
const now = Date.now();
return shifts.filter((s) => s.start - now > 0 && s.start - now <= 2 * 60 * 60 * 1000);
}
// Easy to test: the clock is a parameter, with the real one as the default.
function startingSoon(shifts, now = Date.now()) {
const twoHours = 2 * 60 * 60 * 1000;
return shifts.filter((s) => s.start - now > 0 && s.start - now <= twoHours).map((s) => s.area);
}
const at = (h, m = 0) => Date.UTC(2027, 10, 20, h, m);
const shifts = [
{ area: 'Warehouse', start: at(9, 0) },
{ area: 'Lunch counter', start: at(11, 30) },
{ area: 'Pick-up desk', start: at(12, 0) },
{ area: 'Youth garden', start: at(14, 0) },
];
console.log('At 10:00 ->', startingSoon(shifts, at(10)));
console.log('At 12:30 ->', startingSoon(shifts, at(12, 30)));
console.log('At 9:59 ->', startingSoon(shifts, at(9, 59)));At 10:00 -> [ "Lunch counter", "Pick-up desk" ] At 12:30 -> [ "Youth garden" ] At 9:59 -> [ "Lunch counter" ]
What this code does
startingSoonHard reads Date.now itself, so its result depends on when it runs and a test cannot control it. startingSoon takes the current time as a parameter that defaults to the real clock, so production code calls it the same way while a test passes any time it likes. The three calls test the panel at three moments with no waiting and no surprises.
The same idea works for every dependency: pass in the function that fetches shifts, the storage object and the function that sends reminders. In larger code, a module can export a function that creates the panel from an object of dependencies. Gareth calls this "asking for things rather than reaching for them", and it is the single most useful habit for testable code.
Stubs
A stub returns answers the test chooses. It lets a test try situations that are hard to set up for real: an empty day, a day with forty shifts, or a server that returns an error. The dashboard's loader asks a getShifts function for today's shifts and turns the result into rows for the panel, or an error message.
async function loadPanel(getShifts) {
try {
const shifts = await getShifts('2027-11-20');
if (shifts.length === 0) return 'No shifts today';
return shifts.map((s) => `${s.area}: ${s.spacesLeft} spaces left`).join('; ');
} catch (err) {
return 'Could not load shifts (' + err.message + ')';
}
}
const stubs = {
'a normal day': async () => [{ area: 'Lunch counter', spacesLeft: 2 }, { area: 'Warehouse', spacesLeft: 0 }],
'an empty day': async () => [],
'the server is down': async () => { throw new Error('503 Service Unavailable'); },
};
for (const [situation, stub] of Object.entries(stubs)) {
console.log(situation.padEnd(20), '->', await loadPanel(stub));
}a normal day -> Lunch counter: 2 spaces left; Warehouse: 0 spaces left an empty day -> No shifts today the server is down -> Could not load shifts (503 Service Unavailable)
What this code does
loadPanel receives the function that fetches shifts, so each test can pass a stub instead of the real API client. The three stubs return a normal day, an empty day and an error, and the loop shows how the panel handles each one. Testing the error message against the real server would mean waiting for it to fail.
Spies
A spy records every call: how many there were and what arguments each one received. Tests use spies to check that code did something, such as sending a reminder, without the side effect really happening. Vitest creates a spy with vi.fn(), and Jest with jest.fn(); both record calls in a mock property and add matchers such as toHaveBeenCalledTimes and toHaveBeenCalledWith.
function spy(impl = () => undefined) {
const fn = (...args) => { fn.calls.push(args); return impl(...args); };
fn.calls = [];
return fn;
}
// The code under test sends one reminder per volunteer who has not confirmed.
function sendReminders(signups, send) {
for (const s of signups) if (!s.confirmed) send(s.email, `Reminder: ${s.area} at ${s.time}`);
}
const send = spy();
sendReminders([
{ email: 'ana@example.org', area: 'Lunch counter', time: '11:30', confirmed: false },
{ email: 'ben@example.org', area: 'Warehouse', time: '9:00', confirmed: true },
{ email: 'chi@example.org', area: 'Pick-up desk', time: '12:00', confirmed: false },
], send);
console.log('calls:', send.calls.length);
for (const [to, text] of send.calls) console.log(' ', to, '|', text);
console.log('Ben was not reminded:', !send.calls.some(([to]) => to.startsWith('ben')));calls: 2 ana@example.org | Reminder: Lunch counter at 11:30 chi@example.org | Reminder: Pick-up desk at 12:00 Ben was not reminded: true
What this code does
spy returns a function that pushes its arguments onto a calls array every time it is called and then runs an optional implementation. sendReminders receives the spy instead of the real email sender, so no email is sent, and the test can read exactly who would have received what. This is the same idea as vi.fn and jest.fn, with the bookkeeping written out.
import { expect, test, vi } from 'vitest';
import { sendReminders } from './reminders';
test('reminds only volunteers who have not confirmed', () => {
const send = vi.fn();
sendReminders(
[
{ email: 'ana@example.org', area: 'Lunch counter', time: '11:30', confirmed: false },
{ email: 'ben@example.org', area: 'Warehouse', time: '9:00', confirmed: true },
],
send,
);
expect(send).toHaveBeenCalledTimes(1);
expect(send).toHaveBeenCalledWith('ana@example.org', 'Reminder: Lunch counter at 11:30');
});What this code does
vi.fn creates a spy that does nothing and records its calls. toHaveBeenCalledTimes checks the number of calls, and toHaveBeenCalledWith checks that one of them had exactly those arguments. In Jest the same test uses jest.fn and the same two matchers.
vi.spyOn(object, 'method') wraps an existing method in a spy, so the real method still runs while the calls are recorded, and it can also replace the method's implementation for one test. Spies created that way must be put back afterwards, either with mockRestore or by turning on Vitest's restoreMocks setting, so that one test's spy does not leak into the next.
Fakes
A fake is a small working implementation of a dependency. Where a stub returns canned answers, a fake has real behaviour, just a simpler version of it. The counter page keeps the day's running tally in localStorage so that it survives a page reload, and the code that saves and loads the tally can be tested against a fake storage object that keeps values in a Map.
class MemoryStorage {
#data = new Map();
getItem(key) { return this.#data.has(key) ? this.#data.get(key) : null; }
setItem(key, value) { this.#data.set(key, String(value)); }
removeItem(key) { this.#data.delete(key); }
clear() { this.#data.clear(); }
get length() { return this.#data.size; }
}
function saveTally(storage, day, tally) { storage.setItem('tally:' + day, JSON.stringify(tally)); }
function loadTally(storage, day) {
const text = storage.getItem('tally:' + day);
return text === null ? { orders: 0, cents: 0 } : JSON.parse(text);
}
const storage = new MemoryStorage();
console.log('before saving:', loadTally(storage, '2027-11-20'));
saveTally(storage, '2027-11-20', { orders: 14, cents: 8360 });
console.log('after saving: ', loadTally(storage, '2027-11-20'));
console.log('another day: ', loadTally(storage, '2027-11-21'));
console.log('stored as: ', storage.getItem('tally:2027-11-20'), '| keys:', storage.length);before saving: { orders: 0, cents: 0 }
after saving: { orders: 14, cents: 8360 }
another day: { orders: 0, cents: 0 }
stored as: {"orders":14,"cents":8360} | keys: 1What this code does
MemoryStorage has the same methods as the browser's localStorage, including turning every value into a string, but keeps everything in a private Map. saveTally and loadTally receive the storage object, so tests can pass a fresh fake each time. Each test starts empty and leaves nothing behind for the next one.
Fakes are often the best double because tests that use them check behaviour rather than calls. The test above does not care whether loadTally called getItem once or twice; it cares that a saved tally comes back. If Mira later changes how the tally is stored, the tests still pass as long as the behaviour is right.
Fake timers
Code that uses setTimeout or setInterval is awkward to test with real time. The counter page's search box waits 300 milliseconds after the last key press before filtering the menu, so that it does not filter on every letter, a technique called debouncing from JS-110. A test that really waited would be slow and could still be flaky. Fake timers replace the timer functions with versions that only move when the test says so.
// A tiny fake clock: timers run only when the test advances time.
function fakeClock() {
let now = 0;
const timers = [];
return {
setTimeout(fn, ms) { const t = { at: now + ms, fn }; timers.push(t); return t; },
clearTimeout(t) { const i = timers.indexOf(t); if (i >= 0) timers.splice(i, 1); },
advance(ms) {
now += ms;
timers.sort((a, b) => a.at - b.at);
while (timers.length && timers[0].at <= now) timers.shift().fn();
},
};
}
function debounce(fn, ms, clock) {
let timer = null;
return (...args) => {
if (timer) clock.clearTimeout(timer);
timer = clock.setTimeout(() => fn(...args), ms);
};
}
const clock = fakeClock();
const searches = [];
const search = debounce((text) => searches.push(text), 300, clock);
search('s'); clock.advance(100);
search('so'); clock.advance(100);
search('sou'); clock.advance(299);
console.log('after 499 ms:', searches);
clock.advance(1);
console.log('after 500 ms:', searches);after 499 ms: [] after 500 ms: [ "sou" ]
What this code does
fakeClock keeps its own idea of the time and a list of pending timers, and runs a timer only when advance moves the time past it. debounce receives the clock, so the test can drive it: three quick key presses keep restarting the 300 millisecond wait. Nothing runs until 300 milliseconds after the last press, and the test proves it to the millisecond without waiting at all.
import { afterEach, expect, test, vi } from 'vitest';
import { debounce } from './debounce';
afterEach(() => {
vi.useRealTimers();
});
test('runs once, 300 ms after the last call', () => {
vi.useFakeTimers();
const search = vi.fn();
const debounced = debounce(search, 300);
debounced('s');
vi.advanceTimersByTime(100);
debounced('so');
vi.advanceTimersByTime(299);
expect(search).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(search).toHaveBeenCalledTimes(1);
expect(search).toHaveBeenCalledWith('so');
});What this code does
vi.useFakeTimers replaces setTimeout, setInterval and Date with fake versions for this test, so debounce does not need a clock parameter. vi.advanceTimersByTime moves the fake time forward and runs any timers that are due. The afterEach hook puts the real timers back so that other tests are not affected; vi.setSystemTime can also set the fake date, for tests like the starting-soon panel.
Mocking modules and the network
Sometimes a dependency is not passed in but imported. Vitest's vi.mock('./api') and Jest's jest.mock('./api') replace a whole module for the test file, so every import of it receives a double. Module mocking is powerful and occasionally necessary, for example with a third-party library that cannot be injected, but it hides the dependency inside the test setup, so Brightwater prefers injection where it can.
For code that calls fetch, the usual choice is to intercept requests rather than mock fetch itself. Mock Service Worker (MSW) is a library that answers requests made by the code with responses defined in the test, in Node.js and in the browser. The code under test uses fetch exactly as in production, and the test defines what the "server" says.
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { afterAll, afterEach, beforeAll, expect, test } from 'vitest';
import { getShifts } from './api-client';
const server = setupServer(
http.get('/api/v1/shifts', () =>
HttpResponse.json({ data: [{ area: 'Lunch counter', spacesLeft: 2 }] }),
),
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('reads shifts from the API', async () => {
expect(await getShifts('2027-11-20')).toEqual([{ area: 'Lunch counter', spacesLeft: 2 }]);
});What this code does
setupServer creates a request interceptor with one handler, which answers GET requests to /api/v1/shifts with a JSON body shaped like Theo's API. The hooks start the interceptor before the tests, reset any handlers a test added after each one and stop it at the end. getShifts calls fetch as usual and never knows the response came from the test.
When doubles make tests worse
Test doubles are a tool, and like any tool they can be overused. A test that replaces everything ends up testing the doubles. Gareth's checklist for the block is short.
- Replace what is slow, unpredictable or has side effects: the clock, the network, storage, email, printing. Keep the code's own pure functions real.
- Prefer fakes and stubs to strict mocks. Checking every call a function makes ties the test to how the code works rather than what it does, so harmless refactoring breaks it.
- Keep doubles honest. A stub that returns data Theo's API would never return proves nothing. Build stubs from real example responses, and keep them in one place.
- Restore what you change. Fake timers, spies on real objects and mocked modules must be undone after each test.
- Test the real thing somewhere. Unit tests with doubles are backed up by a few end-to-end tests that use the real page and, in the staging environment, Theo's real server, as Lesson 9 shows.
Common mistakes
MistakeA mock and a stub are the same thing.
InsteadA stub supplies answers; a mock or spy is checked for how it was called. Use the one that matches what the test checks.
MistakeMock every function the code calls.
InsteadReplace only dependencies that are slow, unpredictable or have side effects; keep the code's own logic real.
MistakeFake timers clean up after themselves.
InsteadCall vi.useRealTimers in afterEach, or the fake time leaks into other tests.
MistakeA stub can return any convenient shape.
InsteadBase stubs on real responses, or the tests pass while production fails.
MistakeModule mocking is the first choice.
InsteadPrefer passing dependencies in. Module mocks hide the dependency and are easy to get wrong.
Summary and key terms
- A test double replaces a dependency, such as the clock, the network, storage or a side effect, with something the test controls.
- Kinds include dummies, stubs that return fixed answers, spies that record calls, mocks with expectations and fakes that are simple working implementations.
- Dependency injection, passing dependencies in as parameters with real defaults, makes doubles easy to use.
- Vitest's vi.fn and Jest's jest.fn create spies, with matchers such as toHaveBeenCalledTimes and toHaveBeenCalledWith; vi.spyOn wraps an existing method.
- Fakes such as an in-memory storage test behaviour rather than calls.
- Fake timers, with vi.useFakeTimers and vi.advanceTimersByTime, test debouncing and other timing without waiting; vi.setSystemTime fixes the date. vi.mock replaces whole modules, and Mock Service Worker answers network requests.
- Replace only what is slow, unpredictable or has side effects, keep doubles faithful to the real thing and restore everything after each test.
- test double
- Any object or function that stands in for a real dependency during a test.
- dependency
- Something a unit of code relies on, such as the clock, an API or storage.
- stub
- A test double that returns fixed answers.
- spy
- A test double that records the calls made to it.
- mock
- A test double with expectations about how it will be called, checked by the test.
- fake
- A simplified but working implementation of a dependency, such as in-memory storage.
- dependency injection
- Giving code its dependencies as parameters instead of letting it create or find them.
- fake timers
- Replacements for setTimeout, setInterval and Date that move only when the test advances them.
- debounce
- Delaying an action until a burst of events has stopped for a set time.
- Mock Service Worker
- A library that intercepts network requests and answers them with responses defined in tests.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Which kind of double would you use to check that a reminder was sent to the right address?
Show answer
A spy, such as vi.fn, then toHaveBeenCalledWith.
How does a default parameter help testing?
Show answer
Production calls use the real dependency by default, while tests can pass a double.
Why is an in-memory fake often better than a strict mock of localStorage?
Show answer
It tests behaviour, so the test survives changes to how the code uses storage.
What do vi.useFakeTimers and vi.advanceTimersByTime do?
Show answer
Replace the timer functions with fakes, then move fake time forward and run due timers.
Why should stubs be based on real API responses?
Show answer
So the tests reflect what the code will really receive; invented shapes can hide bugs.
Try it yourself
Build a spy
Complete makeSpy(impl) so that it returns a function that records every call's arguments in spy.calls, then returns whatever impl returns.
Also give the spy a calledWith(...args) method that returns true if any recorded call had exactly those arguments.
function makeSpy(impl = () => undefined) {
const spy = (...args) => impl(...args);
spy.calls = [];
spy.calledWith = (...args) => false;
return spy;
}
const print = makeSpy((ticket) => 'printed ' + ticket);
console.log(print('A-101'));
print('A-102');
console.log(print.calls.length);
console.log(print.calledWith('A-102'), print.calledWith('A-103'));Try it yourself
Test with a fake clock
isLate(shift, now) should return true when a volunteer has not checked in and it is more than 10 minutes after the shift's start time. Times are minutes since midnight.
The starter has an off-by-one mistake. Fix isLate so that all five checks print ok.
function isLate(shift, now) {
return !shift.checkedIn && now - shift.start >= 10;
}
const shift = { start: 11 * 60 + 30, checkedIn: false };
const cases = [[11 * 60 + 30, false], [11 * 60 + 40, false], [11 * 60 + 41, true], [12 * 60, true]];
for (const [now, want] of cases) console.log(isLate(shift, now) === want ? 'ok' : 'WRONG at ' + now);
console.log(isLate({ ...shift, checkedIn: true }, 12 * 60) === false ? 'ok' : 'WRONG for a checked-in volunteer');Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.