Advanced Mocking Techniques
What you'll build
A test suite for a user service that mocks a database client and an email sender, demonstrating partial mocks, spy methods, and module-level mocking.
Goals
- Create partial mocks with jest.fn
- Spy on existing methods without replacing them
- Mock entire modules with jest.mock
- Verify mock calls and interactions
Prerequisites
- Basic mocking with jest.fn
- ES module imports
- Async/await in tests
Steps
- 1
Create the service to test
Create a UserService that depends on a database client and an email sender. These dependencies will be mocked in tests.
Code// src/services/UserService.ts import { dbClient } from '../db/client'; import { emailSender } from '../email/sender'; export class UserService { async createUser(email: string, name: string) { const user = await dbClient.insert('users', { email, name }); await emailSender.sendWelcome(email, name); return user; } async getUser(id: number) { return dbClient.findById('users', id); } async deleteUser(id: number) { const user = await this.getUser(id); if (!user) throw new Error('User not found'); await dbClient.delete('users', id); await emailSender.sendGoodbye(user.email, user.name); } }Expected result
UserService with three methods, depending on dbClient and emailSender.
- 2
Mock modules with jest.mock
Use jest.mock to replace entire modules. This is the most common way to mock dependencies in Jest/Vitest.
Codeimport { UserService } from '../services/UserService'; import { dbClient } from '../db/client'; import { emailSender } from '../email/sender'; jest.mock('../db/client'); jest.mock('../email/sender'); const service = new UserService(); describe('UserService.createUser', () => { beforeEach(() => jest.clearAllMocks()); it('inserts user and sends welcome email', async () => { (dbClient.insert as jest.Mock).mockResolvedValue({ id: 1, email: 'a@b.com', name: 'A' }); const user = await service.createUser('a@b.com', 'A'); expect(user).toEqual({ id: 1, email: 'a@b.com', name: 'A' }); expect(dbClient.insert).toHaveBeenCalledWith('users', { email: 'a@b.com', name: 'A' }); expect(emailSender.sendWelcome).toHaveBeenCalledWith('a@b.com', 'A'); }); });Expected result
The test passes — dbClient and emailSender are mocked, and their calls are verified.
- 3
Spy on methods
Use jest.spyOn to observe a method's calls without replacing its implementation. Spies are useful for verifying interactions while keeping real behavior.
Codedescribe('UserService.getUser', () => { it('delegates to dbClient.findById', async () => { const spy = jest.spyOn(dbClient, 'findById').mockResolvedValue({ id: 1, name: 'A' }); const user = await service.getUser(1); expect(user).toEqual({ id: 1, name: 'A' }); expect(spy).toHaveBeenCalledWith('users', 1); spy.mockRestore(); }); });Expected result
The spy verifies findById was called with the right arguments.
- 4
Test error handling with mock rejection
Use mockRejectedValue to simulate a dependency failure and verify your service handles it correctly.
Codedescribe('UserService.deleteUser error handling', () => { beforeEach(() => jest.clearAllMocks()); it('throws when user not found', async () => { jest.spyOn(dbClient, 'findById').mockResolvedValue(null); await expect(service.deleteUser(999)).rejects.toThrow('User not found'); expect(dbClient.delete).not.toHaveBeenCalled(); }); it('sends goodbye email on successful delete', async () => { jest.spyOn(dbClient, 'findById').mockResolvedValue({ id: 1, email: 'a@b.com', name: 'A' }); (dbClient.delete as jest.Mock).mockResolvedValue(undefined); await service.deleteUser(1); expect(emailSender.sendGoodbye).toHaveBeenCalledWith('a@b.com', 'A'); }); });Expected result
Both error and success paths are tested — the service handles missing users and sends emails correctly.
- 5
Create a mock factory
Use jest.mock with a factory function for full control over the mock implementation. This is useful when the module has complex exports.
Codejest.mock('../db/client', () => ({ dbClient: { insert: jest.fn(), findById: jest.fn(), delete: jest.fn(), update: jest.fn(), }, })); // Now you can configure each method independently beforeEach(() => { (dbClient.insert as jest.Mock).mockImplementation((table, data) => Promise.resolve({ id: Math.random(), ...data }) ); });Expected result
The factory gives full control — each method is a fresh mock with custom behavior.
Try it yourself
import { UserService } from '../services/UserService';
jest.mock('../db/client');
jest.mock('../email/sender');
// TODO: write tests
jest.mock('../db/client', () => ({
dbClient: { insert: jest.fn(), findById: jest.fn(), delete: jest.fn() },
}));What you learned
You mastered advanced mocking — module mocks, spies, mock factories, and rejection testing. These let you isolate any code from its dependencies and test all interaction paths.
Related Resources
Related Lessons
- Mocking
Replacing dependencies.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.