Mocking and test doubles

Topic 3 of 3 in Testing7 min readIntermediateFree course

Overview

Some dependencies make tests slow, flaky or impossible: an email service that would send real emails, a payment provider that would charge real cards, a third-party API with rate limits, the system clock that never stops moving. Test doubles replace them with stand-ins you control.

Used well, doubles make tests fast and reliable. Overused, they produce tests that pass while the real system is broken. This topic covers both the technique and the judgement.

Kinds of test double

The signupService under test depends on usersRepo backed by Postgres, a mailer that calls an email API, and a clock using Date.now(). In tests these are replaced with an in-memory repository (a fake), mock.fn() (a spy), and a fixed time (a stub). Passing dependencies in lets tests choose real or fake versions without patching modules.

Double What it is Example
Fake a simplified working implementation an in-memory repository instead of Postgres
Stub returns canned answers a rates client that always returns 83.2
Spy / mock records how it was called, so you can check a mailer that remembers each send call

People often say “mock” for all of these — that’s fine, as long as you know which you need.

Dependency injection makes it easy

The layered structure from Structuring an API project passes dependencies into each service:

JavaScript
// src/signup.service.js
export function makeSignupService({ usersRepo, mailer, now = () => new Date() }) {
  return {
    async signup({ email, name }) {
      const user = await usersRepo.insert({ email, name, createdAt: now() });
      try {
        await mailer.send({ to: email, template: 'welcome', data: { name } });
      } catch (err) {
        console.error('Welcome email failed', err); // don't fail sign-up for this
      }
      return user;
    },
  };
}

In production you pass the real repository and mailer. In tests you pass doubles. No special tooling, no patching of imports — just arguments. Even the clock is a dependency here, which makes time-based behaviour easy to test.

Spies with mock.fn()

node:test includes a mocking API. mock.fn() creates a function that records every call:

JavaScript
import { it, mock } from 'node:test';
import assert from 'node:assert/strict';

it('sends a welcome email', async () => {
  const mailer = { send: mock.fn(async () => {}) };
  const usersRepo = { insert: async (u) => ({ id: 1, ...u }) };
  const service = makeSignupService({ usersRepo, mailer });

  await service.signup({ email: 'asha@example.com', name: 'Asha' });

  assert.equal(mailer.send.mock.callCount(), 1);
  const [message] = mailer.send.mock.calls[0].arguments;
  assert.equal(message.to, 'asha@example.com');
  assert.equal(message.template, 'welcome');
});

Pass an implementation to control what it returns or throws:

JavaScript
const failingMailer = { send: mock.fn(async () => { throw new Error('SMTP down'); }) };

Replacing methods with mock.method()

When a dependency isn’t injected — say, a module-level object — you can temporarily replace one method:

JavaScript
import { mailer } from '../src/mailer.js';

it('logs when sending fails', (t) => {
  t.mock.method(mailer, 'send', async () => { throw new Error('down'); });
  // …the original send is restored automatically when this test ends
});

Using t.mock (the test context’s mock tracker) restores everything after the test. With the top-level mock, call mock.restoreAll() in an afterEach.

Controlling time

Code with timers, expiry or “created at” dates is painful to test with the real clock. mock.timers lets you fast-forward time instantly:

JavaScript
it('expires the code after 5 minutes', (t) => {
  t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: new Date('2026-12-03T10:00:00Z') });

  const otp = createOtp();            // uses Date.now() internally
  assert.equal(otp.isValid(), true);

  t.mock.timers.tick(5 * 60 * 1000 + 1);
  assert.equal(otp.isValid(), false);
});

A five-minute timeout tested in a millisecond.

Faking HTTP calls

For code that calls external APIs with fetch, the cleanest option is to wrap each service in a small client (see Making HTTP requests) and inject a stub:

JavaScript
const ratesClient = { getRate: async () => 83.2 };
const service = makePricingService({ ratesClient });

When you need to test the client itself, you can replace the global fetch for one test:

JavaScript
it('throws on a 503 from the rates API', async (t) => {
  t.mock.method(globalThis, 'fetch', async () => new Response('busy', { status: 503 }));
  await assert.rejects(getRate('USD', 'INR'), /503/);
});

Libraries such as undici’s MockAgent or msw intercept requests at the network level for more realistic tests.

What to mock — and what not to

Mock things you don’t own or can’t run in a test: email and SMS providers, payment gateways, third-party APIs, the clock, randomness.

Prefer the real thing for code you own: your own services, validation, and — in API tests — ideally your database. Every double is an assumption about how the real dependency behaves. If the assumption is wrong, the test passes and production fails.

Warning signs of over-mocking:

  • Tests that check how code works (expect(repo.query).toHaveBeenCalledWith(…SQL…)) instead of what it does.
  • Tests that break whenever you refactor, even though behaviour didn’t change.
  • A test that needs ten mocks to run — often a sign the code under test does too much.

Contract tests for fakes

If you use an in-memory fake repository, run the same test suite against both the fake and the real Postgres repository. That proves the fake behaves like the real thing, so tests using it can be trusted:

JavaScript
for (const [name, makeRepo] of [['memory', makeMemoryCoursesRepo], ['postgres', () => makePgCoursesRepo(pool)]]) {
  describe(`courses repository (${name})`, () => {
    it('finds titles case-insensitively', async () => {
      const repo = makeRepo();
      await repo.insert({ title: 'Node.js', description: '', level: 'Beginner' });
      assert.ok(await repo.findByTitle('NODE.JS'));
    });
  });
}

The goal is confidence, not isolation. Use doubles to remove slowness and unpredictability, and keep as much real code in the test as you can.

Exercise

Test a sign-up service

makeSignupService({ usersRepo, mailer, now }) saves a user with createdAt: now() and sends a welcome email. Test it with an in-memory fake repo, a mock.fn() mailer and a fixed clock. Check the user was saved with the right timestamp, the mailer was called once with the right address, and that a mailer failure doesn't stop sign-up.

JavaScript
import { it, mock } from 'node:test';
import assert from 'node:assert/strict';
import { makeSignupService } from '../src/signup.service.js';

Summary

  • Test doubles stand in for real dependencies: fakes (working simplified versions), stubs (canned answers) and spies/mocks (record calls).
  • Inject dependencies so tests can pass doubles in without patching modules.
  • mock.fn() creates a spy; mock.method(obj, 'name') replaces a method and can be restored.
  • mock.timers controls setTimeout and Date so time-based code tests instantly.
  • Mock what you don’t own and can’t run (email, payments, third-party APIs); prefer real code elsewhere.