Mocking and Stubbing: Test Doubles Explained
Mocks, stubs, fakes and spies are different test doubles. Learn what each is for, when to use them, and why over-mocking makes tests brittle.
By Velloreth
The family of test doubles
A test double is any object that stands in for a real dependency during a test. The term comes from film, where a stunt double replaces the actor.
There are several kinds, and the names are used loosely. The distinctions matter because they lead to different kinds of tests.
| Kind | What it does |
|---|---|
| Dummy | Passed around but never used |
| Stub | Returns canned answers |
| Spy | Records calls, uses real behaviour |
| Mock | Records calls and verifies expectations |
| Fake | A working simplified implementation |
Stubs
A stub returns predetermined answers so the code under test can proceed.
interface WeatherApi {
getTemperature(city: string): Promise<number>;
}
test('recommends a coat when it is cold', async () => {
const stub: WeatherApi = {
getTemperature: async () => 5, // always returns 5
};
const advice = await getClothingAdvice('London', stub);
expect(advice).toBe('Wear a coat');
});
The stub provides the data the test needs. It does not verify anything; it just answers.
Stubs are the least problematic double. They replace a dependency that would otherwise make the test slow or non-deterministic, and they let you control the input.
Mocks
A mock records calls and lets you assert that specific interactions happened.
test('sends a welcome email on signup', async () => {
const emailMock = { send: jest.fn() };
const service = new SignupService(emailMock);
await service.signup({ email: 'ada@example.com' });
expect(emailMock.send).toHaveBeenCalledWith(
'ada@example.com',
expect.stringContaining('Welcome'),
);
});
The mock verifies that send was called with the right arguments. This is useful when the interaction is the behaviour — sending an email is the point of the feature.
Mocks become problematic when they verify interactions that are implementation details rather than behaviour.
Fakes
A fake is a working implementation with a shortcut that makes it unsuitable for production.
class InMemoryUserRepository implements UserRepository {
private users = new Map<string, User>();
async save(user: User): Promise<void> {
this.users.set(user.id, user);
}
async findById(id: string): Promise<User | null> {
return this.users.get(id) ?? null;
}
async findByEmail(email: string): Promise<User | null> {
return [...this.users.values()].find((u) => u.email === email) ?? null;
}
}
The fake implements the real interface with a Map instead of a database. It behaves like the real thing, so tests using it exercise real logic — the service’s code runs unchanged.
Fakes are usually the best choice. They test behaviour rather than implementation, they survive refactoring, and they are fast.
Spies
A spy wraps a real object and records how it was called, without replacing its behaviour.
test('logs the order total', async () => {
const logger = new Logger();
const spy = jest.spyOn(logger, 'info');
await processOrder(order, logger);
expect(spy).toHaveBeenCalled();
// the real logger still ran
});
The spy observes without replacing. Useful when you want to verify an interaction but still exercise the real implementation.
Why over-mocking is bad
Every mock is a lie about how the real dependency behaves. If you mock everything, the test verifies that your code calls the mocks you wrote — not that the system works.
// Over-mocked: tests nothing real
test('creates a user', async () => {
const repo = { save: jest.fn().mockResolvedValue(undefined) };
const hasher = { hash: jest.fn().mockReturnValue('hashed') };
const validator = { validate: jest.fn().mockReturnValue(true) };
const mailer = { send: jest.fn().mockResolvedValue(undefined) };
const service = new UserService(repo, hasher, validator, mailer);
await service.createUser({ email: 'ada@example.com', password: 'secret' });
expect(repo.save).toHaveBeenCalled();
expect(hasher.hash).toHaveBeenCalled();
expect(validator.validate).toHaveBeenCalled();
expect(mailer.send).toHaveBeenCalled();
});
This test passes even if every one of those classes is broken, because none of them ran. It verifies that the service calls four methods, which is an implementation detail.
The second problem is brittleness. Change the service to batch saves, or to validate inside the repository, and the test fails even though the behaviour is unchanged.
Mock at the boundaries
The rule that prevents over-mocking: mock at the boundaries of your system, not between your own classes.
Boundaries worth mocking:
- External HTTP APIs.
- The system clock.
- Random number generation.
- The file system.
- Email and SMS providers.
- Payment gateways.
- Message queues.
Not worth mocking:
- Your own services and repositories.
- Your own domain objects.
- Pure functions.
For your own classes, use the real implementation or a fake. The test then exercises real logic, and it survives refactoring.
// Good: mock the boundary, use real code inside
test('creates a user and sends a welcome email', async () => {
const repo = new InMemoryUserRepository(); // fake
const mailer = { send: jest.fn() }; // boundary mock
const service = new UserService(repo, mailer);
await service.createUser({ email: 'ada@example.com' });
const saved = await repo.findByEmail('ada@example.com');
expect(saved).not.toBeNull(); // real behaviour
expect(mailer.send).toHaveBeenCalled(); // boundary interaction
});
The repository is a fake, so the real save and lookup logic runs. The mailer is a mock, because it is an external boundary and the interaction is the behaviour.
Mocking time
Time is a boundary, and mocking it is one of the highest-value uses.
interface Clock {
now(): Date;
}
test('marks a subscription expired after the end date', () => {
const clock: Clock = { now: () => new Date('2026-06-01') };
const service = new SubscriptionService(clock);
expect(service.isExpired(new Date('2026-05-31'))).toBe(true);
});
Without this, the test depends on the real clock and will fail on some future date. Injecting the clock makes it deterministic.
Mocking the database
Prefer a fake or a real test database over a mock.
Mocking a database means your tests never run the queries. SQL syntax errors, missing columns, and constraint violations all go undetected until production.
// Bad: the query is never executed
const db = { query: jest.fn().mockResolvedValue([{ id: 1 }]) };
// Good: the query runs against a real schema
const db = await createTestDatabase(); // in-memory SQLite or a container
The trade-off is speed. A real database is slower than a mock. The usual compromise is a fast in-memory database for unit tests and a real one for integration tests.
Keeping mocks honest
A mock is a claim about how a dependency behaves, and claims go stale. Two habits keep them accurate.
Derive the mock from the real interface. In a typed language, declare the mock as the interface type so the compiler catches a missing method.
const mailer: EmailSender = {
send: jest.fn(), // compiler errors if EmailSender gains a method
};
Without the type annotation, adding a method to EmailSender leaves the mock silently incomplete, and the test keeps passing while the real code breaks.
Verify the contract once, for real. A mock encodes your belief about the dependency’s behaviour. If that belief is wrong, every test using the mock is wrong too. One integration test against the real dependency catches this.
// Unit tests use the mock
const mailer = { send: jest.fn() };
// One integration test uses the real client
test('the real mailer accepts the arguments we pass', async () => {
await expect(realMailer.send('ada@example.com', 'Welcome')).resolves.not.toThrow();
});
The integration test is the check on the mock. Without it, a mock that accepts arguments the real service rejects will keep the whole suite green while production fails.
Practical guidance
- Prefer fakes over mocks — they test behaviour and survive refactoring.
- Use stubs to control inputs from slow or non-deterministic dependencies.
- Use mocks only when the interaction is the behaviour.
- Mock at the boundaries — external APIs, time, randomness, I/O.
- Do not mock your own classes — use the real thing or a fake.
- Do not mock the database — use an in-memory or real test database.
- Watch for tests that pass while the system is broken — that is the over-mocking symptom.
- Assert on outcomes, not on call counts, wherever possible.
For the related practices, see unit testing basics and integration vs unit tests. For the broader context, test-driven development guide and why your tests are slow.
Quotable summary
A test double is any object standing in for a real dependency, and the kinds differ in purpose: a stub returns canned answers, a mock records calls and verifies interactions, a fake is a working simplified implementation, and a spy observes without replacing behaviour. Prefer fakes over mocks, because fakes test behaviour and survive refactoring while mocks test implementation and break when it changes. Over-mocking produces tests that pass while the system is broken, since every mock is a lie about how the real dependency behaves. Mock at the boundaries of your system — external APIs, time, randomness, and I/O — not between your own classes, and prefer an in-memory or real test database over a mocked one so queries actually execute.