Test Doubles (Stub, Mock, Fake)

Three kinds of substitute for a real dependency in a test — a stub returns data, a mock asserts on calls, a fake is a real simplified implementation.

Purpose

A test double replaces a real dependency for the purposes of a test. Which kind to reach for depends on what the test actually needs to verify.

The three kinds

// Stub — returns canned data, doesn't care how it's called
const stubApi = { getUser: () => ({ id: 1, name: 'Ada' }) };

// Mock — asserts on HOW it was called
const mockEmailer = { send: vi.fn() };
await notifyUser(mockEmailer);
expect(mockEmailer.send).toHaveBeenCalledWith('[email protected]', 'Welcome!');

// Fake — a real, working, simplified implementation
class FakeDatabase {
  #records = new Map();
  save(id, record) {
    this.#records.set(id, record);
  }
  find(id) {
    return this.#records.get(id);
  }
}

Behavior notes

  • A stub is the simplest: fixed return data, no behavior, no assertions about how it was used.
  • A mock specifically asserts on the interaction itself — which arguments, how many calls — useful when the fact of the call is the behavior under test (an email was sent), not a return value.
  • A fake is a real, working, simplified implementation — often clearer than a mock for anything beyond a single call, because the test exercises genuine behavior (data saved really can be found again) rather than asserting on call mechanics that can pass even when underlying logic is wrong.

Common mistakes

  • Using “mock” as a generic term for any test double, obscuring which specific substitution strategy — and which specific thing being verified — a test actually uses.
  • Over-mocking: asserting on internal call details so precisely that a harmless refactor (same behavior, different internal call pattern) breaks tests that should have kept passing.

Runtime notes

A testing pattern, not a language feature — most test frameworks provide built-in mock/stub helpers, but the concepts apply regardless of which one is in use.

Taught in these lessons

Related reference

Updated 2026-09-03