Skip to content

Test Double

In one line

Test double is the umbrella term for all replacement objects in testing: mocks, stubs, spies, fakes, and dummies.

In simple words

'Test double' is the catch-all term for any fake object that stands in for a real one during testing. The name comes from 'stunt double' in movies — a stand-in for the real actor.

There are five main types of test doubles:

  1. Dummy: A placeholder passed around but never used. Just satisfies a parameter requirement.
  2. Stub: Returns preset values. Replaces real behavior with canned responses.
  3. Spy: Wraps a real function, records calls, and still runs the original.
  4. Mock: A pre-programmed object with expectations about how it should be called.
  5. Fake: A working but simplified implementation (e.g., an in-memory database instead of a real one).

In practice, the terms are often used loosely — people say 'mock' when they mean any test double. The taxonomy comes from Gerard Meszaros' book 'xUnit Test Patterns'.

Example

javascript
// Test doubles: stub, mock, spy, fake

// 1. STUB — replaces a function with a canned return value
const dbStub = { findUser: () => ({ id: 1, name: 'Alice' }) };

// 2. MOCK — stub + verifies the function was called
const mockSend = vi.fn();
notifyUser(mockSend, { id: 1 });
expect(mockSend).toHaveBeenCalledWith(expect.objectContaining({ id: 1 }));

// 3. SPY — wraps real function, records calls without changing behavior
const spy = vi.spyOn(console, 'log');
doWork();
expect(spy).toHaveBeenCalledTimes(2);

// 4. FAKE — simplified working implementation
const fakeClock = { now: () => 1700000000000 }; // fixed time

Four kinds of test doubles: a stub returns canned values, a mock also verifies it was called, a spy wraps a real function to record calls, and a fake is a simplified working implementation (like an in-memory DB).

Related terms

Related Resources

Related Lessons

Decode error messages

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

View errors

← Back to glossary