Skip to content

Advanced Mocking Techniques

Medium ~45 min

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. 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. 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.

    Code
    import { 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: '[email protected]', name: 'A' });
    
        const user = await service.createUser('[email protected]', 'A');
    
        expect(user).toEqual({ id: 1, email: '[email protected]', name: 'A' });
        expect(dbClient.insert).toHaveBeenCalledWith('users', { email: '[email protected]', name: 'A' });
        expect(emailSender.sendWelcome).toHaveBeenCalledWith('[email protected]', 'A');
      });
    });

    Expected result

    The test passes — dbClient and emailSender are mocked, and their calls are verified.

  3. 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.

    Code
    describe('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. 4

    Test error handling with mock rejection

    Use mockRejectedValue to simulate a dependency failure and verify your service handles it correctly.

    Code
    describe('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: '[email protected]', name: 'A' });
        (dbClient.delete as jest.Mock).mockResolvedValue(undefined);
    
        await service.deleteUser(1);
    
        expect(emailSender.sendGoodbye).toHaveBeenCalledWith('[email protected]', 'A');
      });
    });

    Expected result

    Both error and success paths are tested — the service handles missing users and sends emails correctly.

  5. 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.

    Code
    jest.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

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

Look up unfamiliar terms

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

View glossary

Decode error messages

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

View errors

← Back to topic