3.5 Hours

10. Testing Patterns: Mocks, Stubs, and Test Doubles

Patterns

Test doubles are objects that stand in for real dependencies in tests. They include mocks, stubs, spies, and fakes. Understanding test doubles is essential for writing effective unit tests that isolate the code under test.

The key insight is that different test doubles serve different purposes. Stubs provide canned responses. Spies track calls. Mocks verify behavior. Fakes are simplified implementations. Using the right test double for each situation makes your tests cleaner and more maintainable.

This module covers the different types of test doubles and when to use each.

Types of Test Doubles

Stubs provide canned responses to calls. They're used when you need to control the output of a dependency. Spies track calls to a function, recording arguments and call count. Mocks are pre-programmed with expectations and verify behavior. Fakes are simplified implementations that work in tests. Dummies are placeholders that aren't used.

Choosing the right test double is essential for maintainable tests. Use stubs for dependencies that provide data. Use spies when you need to verify calls. Use mocks when you need to verify behavior. Use fakes for complex dependencies like databases.

Mock vs Stub vs Spy

Mocks are about behavior verification. You set expectations and verify they were met. Stubs are about state verification. You return specific values and verify the result. Spies are a hybrid — they track calls without replacing the function. In practice, Jest's jest.fn() can act as a stub, spy, or mock depending on how you use it.

Understanding the differences helps you choose the right tool. Use mocks for external dependencies. Use stubs for internal dependencies. Use spies for functions with side effects.

JavaScript
// Stub: returns canned responses
const stubApi = {
  getUser: jest.fn().mockReturnValue({ id: 1, name: 'Alice' })
};

// Spy: tracks calls
const spy = jest.spyOn(logger, 'log');
// ... code under test ...
expect(spy).toHaveBeenCalledWith('User created');

// Mock: pre-programmed expectations
const mockApi = {
  saveUser: jest.fn().mockImplementation((user) => {
    // Could also verify
    expect(user.name).toBe('Bob');
    return { id: 2, ...user };
  })
};

// Fake: simplified implementation
class FakeDatabase {
  constructor() {
    this.users = [];
  }
  save(user) {
    this.users.push(user);
    return user;
  }
  find(id) {
    return this.users.find(u => u.id === id);
  }
}

Try It Yourself: Using Test Doubles

Follow these steps to practice using different test doubles.

Step 1: Create the code
// userService.js<br>export class UserService {<br> constructor(api, logger) {<br> this.api = api;<br> this.logger = logger;<br> }<br><br> async getUser(id) {<br> this.logger.log(`Fetching user ${id}`);<br> return this.api.fetchUser(id);<br> }<br><br> async createUser(user) {<br> this.logger.log(`Creating user ${user.name}`);<br> return this.api.saveUser(user);<br> }<br>}

Step 2: Write tests with test doubles
// userService.test.js<br>import { UserService } from <strong><code>./userService;

describe(UserService, () => {
test(getUser fetches and logs user, async () => {
// Stub const mockApi = {
fetchUser: jest.fn().mockResolvedValue({ id: 1, name: Alice })
};

// Spy
const mockLogger = {
log: jest.fn()
};

const service = new UserService(mockApi, mockLogger);
const user = await service.getUser(1);

// Verify state expect(user).toEqual({ id: 1, name: Alice });

// Verify behavior (spy)
expect(mockLogger.log).toHaveBeenCalledWith(Fetching user 1);
expect(mockApi.fetchUser).toHaveBeenCalledWith(1);
});

test(createUser saves and logs user, async () => {
const mockApi = {
saveUser: jest.fn().mockResolvedValue({ id: 2, name: Bob })
};
const mockLogger = { log: jest.fn() };

const service = new UserService(mockApi, mockLogger);
const user = await service.createUser({ name: Bob });

expect(user).toEqual({ id: 2, name: Bob });
expect(mockLogger.log).toHaveBeenCalledWith(Creating user Bob);
expect(mockApi.saveUser).toHaveBeenCalledWith({ name: Bob });
});
});

Try It Yourself: Create a fake database for testing. Use it to test a service that depends on a database.

Knowledge Check

Ready to test your understanding of 10. Testing Patterns: Mocks, Stubs, and Test Doubles?

Back