Skip to content

Test Doubles

Understand mocks, stubs, spies, and fakes — the stand-ins that keep tests isolated.

What you'll learn

  • What a test double is and why isolation requires them
  • The four kinds: mocks, stubs, spies, and fakes
  • When to use each kind and the trade-offs
  • How test doubles prevent tests from touching real systems

Concept

The Problem of Dependencies

Real code calls other code: a service calls a repository, a component calls an API, a function reads the clock. If a unit test lets those calls reach the real systems, it becomes slow, non-deterministic, and tests more than one thing. A test double is a controlled stand-in for a real dependency, letting the test focus on the unit under test.

The Four Kinds

Gerard Meszaros classified test doubles into four kinds. A dummy is passed but never used (just to satisfy a parameter). A stub returns canned answers so the unit can proceed. A spy records how it was called (arguments, call count) while optionally delegating to the real implementation. A mock is a stub pre-programmed with expectations — the test fails if the expected calls do not happen. A fake is a working but simplified implementation, like an in-memory database.

Choosing the Right Double

Use a stub when you just need the dependency to return a value. Use a spy when you need to verify that your code called the dependency correctly (the right method, the right arguments). Use a mock when the interaction itself is the contract — for example, that saving a user calls exactly one email send. Use a fake when a simplified real implementation gives better confidence than canned values, such as an in-memory repository.

Trade-offs

Test doubles isolate and speed up tests, but over-mocking couples tests to implementation details: change a call site and many mocks break even though behavior is correct. Prefer fakes and stubs over mocks, and mock at architectural boundaries (external APIs, the filesystem) rather than between your own classes. The next lessons dive into each kind in detail.

In Practice

A good heuristic: if removing the double and using the real dependency would make the test slow or non-deterministic, the double is justified; if it would only make the test slightly slower but still correct, prefer the real thing. Fakes often give the best value — an in-memory repository behaves like the real one (it saves, finds, deletes) without the database cost, so your test exercises real logic rather than canned responses. Save mocks for the moments where the interaction itself is the contract: "placing an order sends exactly one confirmation email." When you find yourself mocking five collaborators to test one method, step back — the method may have too many responsibilities, and the test is telling you to refactor. The doubles should serve the design, not fight it.

Example

              import { describe, it, expect, vi } from "vitest";

// A stub: returns a fixed value so the unit can run
const stubRepo = { findById: vi.fn().mockResolvedValue({ id: 1, name: "Ada" }) };

// A spy: wraps a real function to observe calls
const realSend = (msg: string) => console.log(msg);
const spySend = vi.fn(realSend);

// A mock: asserts the interaction happened
describe("order service", () => {
  it("sends exactly one confirmation email", async () => {
    const service = new OrderService(stubRepo, spySend);
    await service.place({ id: 1, total: 99 });
    expect(spySend).toHaveBeenCalledTimes(1);
    expect(spySend).toHaveBeenCalledWith(expect.stringContaining("confirmed"));
  });
});
            

stubRepo feeds data, spySend observes the email call, and the mock expectation verifies the contract. Each double has a single, clear purpose.

Try it

  • JSON Formatter

    Inspect the canned data your stubs return.

  • Code Diff

    Compare recorded call arguments against expected ones.

Common mistakes

The mistake

Mocking every class until the test verifies only mocks

The fix

Mock at boundaries (I/O, external services). Let your own domain objects interact for real so the test has meaning.

The mistake

Confusing a stub with a mock

The fix

A stub provides answers; a mock verifies expectations. If you do not assert call count or arguments, it is a stub, not a mock.

Practice Test Doubles

6 exercises

Practice Test Doubles

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors