Course contentsShow
← JavaScript
Lesson 2699 of 2,72354. Testing in JavaScriptFree lesson

Module Mocking with jest.mock()

Replace entire modules in tests, automatically mocking all exports or providing custom implementations.

Module Mocking with jest.mock()

You'll learn: How to replace entire modules in your tests, automatically mocking all their exports or providing your own custom implementations.

The Big Picture

When testing code that imports external modules (like database clients, API wrappers, or utility libraries), you often want to replace the entire module rather than mocking individual functions. jest.mock() intercepts the import or require statement and substitutes the real module with a mocked version—giving you complete control over what your test code receives.

Think of it like a stunt double in a movie: the audience (your test) thinks it's interacting with the real actor (the actual module), but behind the scenes, a controlled stand-in is performing all the actions exactly as you've scripted them.

How It Works

Call jest.mock('module-name') at the top level of your test file (before any imports). Jest automatically mocks all exported functions from that module:

// At the top of your test file
jest.mock('./database');

import db from './database';
import { getUserById } from './userService';

// All functions in 'database' are now jest.fn() mocks
db.query.mockResolvedValue({ rows: [{ id: 1, name: 'Alice' }] });

test('fetches user data', async () => {
  const user = await getUserById(1);
  expect(user.name).toBe('Alice');
  expect(db.query).toHaveBeenCalledWith('SELECT * FROM users WHERE id = $1', [1]);
});

You can also provide a custom implementation as a second argument to control exactly what the mock exports.

Key Takeaway: jest.mock() replaces entire modules at the import level, automatically creating mocked versions of all exports—perfect for isolating units of code that depend on external resources or complex libraries.