What is Mocking?

Mocking replaces a real dependency (an API client, database, timer, module or function) with a controllable fake during a test, so you can test a unit in isolation, simulate edge cases and verify how the dependency was used.

Kinds of test doubles

  • Stub: returns canned data (getUser always resolves to Ada).
  • Spy: records calls and arguments, optionally passing through to the real function.
  • Mock: a stub or spy with expectations you assert on ("called once with these args").
  • Fake: a working lightweight implementation (an in-memory database).

What to mock

  • Network: prefer MSW (Mock Service Worker), which intercepts requests at the network level, so your real fetch code runs. Your tests stay realistic and survive refactors.
  • Time and randomness: fake timers, a fixed Date, seeded random values.
  • Expensive or side-effecting services: payments, email, analytics.
  • Browser APIs missing in the test environment (IntersectionObserver, matchMedia).

What not to mock

  • The unit you are testing.
  • Simple pure helpers and your own internal modules; mocking them couples tests to implementation and lets real bugs slip through.
  • Too much in general: heavily mocked tests can pass while the real integration is broken. Balance them with integration tests.

Dependency injection makes mocking easy

If a function receives its dependencies as arguments (or via a context), tests can pass fakes without any mocking framework.

Hygiene

Reset or restore mocks between tests so state does not leak (vi.restoreAllMocks(), jest.restoreAllMocks()).

Code example

js
1// Code under test receives its dependencies (easy to mock)
2async function sendWelcome(userId, { api, mailer, now = () => new Date() }) {
3 const user = await api.getUser(userId);
4 if (!user.email) return { sent: false, reason: "no email" };
5 await mailer.send({ to: user.email, subject: `Welcome, ${user.name}!`, at: now().toISOString() });
6 return { sent: true };
7}
8
9// A tiny hand-rolled spy (frameworks give you vi.fn() / jest.fn())
10function fn(impl = () => {}) {
11 const spy = (...args) => (spy.calls.push(args), impl(...args));
12 spy.calls = [];
13 return spy;
14}
15
16// Stubs and spies for this test
17const api = { getUser: fn(async (id) => ({ id, name: "Ada", email: "ada@example.com" })) };
18const mailer = { send: fn(async () => {}) };
19const fixedNow = () => new Date("2026-01-01T09:00:00Z");
20
21const result = await sendWelcome(7, { api, mailer, now: fixedNow });
22console.log(result); // { sent: true }
23console.log(api.getUser.calls); // [[7]]
24console.log(mailer.send.calls[0][0]); // { to: "ada@example.com", subject: "Welcome, Ada!", at: "2026-01-01T09:00:00.000Z" }
25
26// Simulate an edge case that's hard to reproduce for real
27const noEmailApi = { getUser: fn(async (id) => ({ id, name: "Linus", email: null })) };
28const mailer2 = { send: fn() };
29console.log(await sendWelcome(8, { api: noEmailApi, mailer: mailer2 }), mailer2.send.calls.length); // { sent: false, reason: "no email" } 0

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app