Jest Mock Functions & Module Mocking: A Deep Dive
Mocking is where most developers either gain a superpower or dig themselves into a maintenance hole. Jest ships with a complete mocking system built in — no extra packages required. But jest.fn(), jest.spyOn(), and jest.mock() each do something distinct, and confusing them leads to brittle tests that pass when they shouldn't or fail for mysterious reasons.
This guide goes deep on all three.
jest.fn() — Creating Mock Functions
jest.fn() creates a standalone mock function. It records every call made to it: arguments, return values, this context, and call order. Out of the box it returns undefined.
const greet = jest.fn();
greet('Alice');
greet('Bob', 'extra');
console.log(greet.mock.calls);
// [['Alice'], ['Bob', 'extra']]
console.log(greet.mock.calls[0][0]); // 'Alice'
console.log(greet.mock.calls.length); // 2The .mock property is the source of truth. It exposes:
.mock.calls— array of argument arrays per call.mock.results— array of{ type, value }per call.mock.instances— array ofthisvalues per call.mock.contexts— same as instances but for arrow functions
Controlling Return Values
const fetchUser = jest.fn();
// Always return the same value
fetchUser.mockReturnValue({ id: 1, name: 'Alice' });
// Return different values on successive calls
fetchUser
.mockReturnValueOnce({ id: 1, name: 'Alice' })
.mockReturnValueOnce({ id: 2, name: 'Bob' })
.mockReturnValue(null); // fallback for all subsequent calls
// Return a resolved/rejected promise
const loadData = jest.fn();
loadData.mockResolvedValue({ data: [] });
loadData.mockRejectedValueOnce(new Error('Network error'));Custom Implementation
When return values aren't enough, use mockImplementation:
const divide = jest.fn().mockImplementation((a, b) => {
if (b === 0) throw new Error('Division by zero');
return a / b;
});
expect(divide(10, 2)).toBe(5);
expect(() => divide(10, 0)).toThrow('Division by zero');mockImplementationOnce works for single-call overrides, falling back to the base implementation afterward.
jest.spyOn() vs jest.fn()
jest.spyOn() wraps an existing method on an object, replacing it with a mock while preserving the original. This matters when you need to:
- Assert that a real method was called with specific arguments
- Temporarily override behavior while keeping the real implementation available for restoration
const calculator = {
add: (a, b) => a + b,
};
const spy = jest.spyOn(calculator, 'add');
calculator.add(2, 3);
expect(spy).toHaveBeenCalledWith(2, 3);
expect(spy).toHaveBeenCalledTimes(1);
// The real implementation still ran
expect(calculator.add(2, 3)).toBe(5);Override the implementation when needed:
jest.spyOn(calculator, 'add').mockReturnValue(42);
expect(calculator.add(2, 3)).toBe(42); // real impl bypassedRestore the original after the test:
afterEach(() => {
jest.restoreAllMocks(); // restores all spyOn mocks to original
});Key difference: jest.fn() creates a new function from scratch. jest.spyOn() replaces a method on an existing object and can restore the original. Use spyOn when you're working with a real object's method; use fn() when you're injecting a dependency directly.
jest.mock() for Module Mocking
jest.mock() intercepts require() and import calls at the module level. Jest hoists jest.mock() calls to the top of the file (before imports), which is why this works even when the mock call appears after the import statement in your source.
import { sendEmail } from './emailService';
jest.mock('./emailService');
test('sends a welcome email on signup', async () => {
sendEmail.mockResolvedValue({ messageId: 'abc123' });
await signupUser('user@example.com');
expect(sendEmail).toHaveBeenCalledWith({
to: 'user@example.com',
subject: 'Welcome!',
});
});After jest.mock('./emailService'), every export from that module becomes a jest.fn(). The module's real code never runs.
Auto-Mocking vs Manual Mocking
Auto-mocking (shown above) replaces all exports with jest.fn(). It's fast but produces mocks with no behavior — you add it per-test via mockReturnValue etc.
Manual mocking gives you a custom factory:
jest.mock('./database', () => ({
connect: jest.fn().mockResolvedValue(true),
query: jest.fn().mockResolvedValue([]),
disconnect: jest.fn(),
}));The factory function runs once. The returned object is what every import or require of that module receives.
The __mocks__ Directory
For mocks you want to reuse across many test files, create a __mocks__ directory adjacent to the module:
src/
services/
emailService.js
__mocks__/
emailService.js ← manual mock// src/services/__mocks__/emailService.js
const sendEmail = jest.fn().mockResolvedValue({ messageId: 'mock-id' });
const getStatus = jest.fn().mockReturnValue('delivered');
module.exports = { sendEmail, getStatus };In your test, calling jest.mock('./emailService') with no factory will automatically use the __mocks__ version.
For Node modules (in node_modules), place the __mocks__ directory at the project root. Node modules are automatically mocked when a __mocks__ file exists — you still need jest.mock('module-name') in your test for local modules, but for node_modules the __mocks__ file is picked up automatically when automock: true is set, or when you call jest.mock() with the package name.
Mocking Default Exports vs Named Exports
Named exports are straightforward — the module factory object's keys match the export names:
jest.mock('./utils', () => ({
formatDate: jest.fn().mockReturnValue('2024-01-01'),
parseDate: jest.fn(),
}));Default exports require a default key:
jest.mock('./UserService', () => ({
default: jest.fn().mockImplementation(() => ({
getUser: jest.fn().mockResolvedValue({ id: 1 }),
saveUser: jest.fn(),
})),
}));When the module uses ES module syntax and you're using Babel or TypeScript transforms, you may also need __esModule: true:
jest.mock('./logger', () => ({
__esModule: true,
default: jest.fn(),
log: jest.fn(),
}));Mocking Specific Methods Only
Sometimes you only want to mock one method and leave the rest real. Use jest.requireActual() inside the factory:
jest.mock('./config', () => {
const actual = jest.requireActual('./config');
return {
...actual,
getFeatureFlag: jest.fn().mockReturnValue(true),
};
});This is essential when the module has side effects or many exports you don't want to stub out manually.
Clearing, Resetting, and Restoring Mocks
These three operations are distinct and matter:
| Method | What it does |
|---|---|
mockFn.mockClear() |
Clears call history (.mock.calls, .mock.results). Keeps implementation. |
mockFn.mockReset() |
Clears call history AND removes mock implementation. Returns undefined. |
mockFn.mockRestore() |
Only for spyOn — restores the original implementation. |
The Jest config equivalents (run automatically between tests):
{
"clearMocks": true,
"resetMocks": false,
"restoreMocks": true
}clearMocks: true is safe and recommended for most projects — it prevents call count leakage between tests. resetMocks: true is more aggressive and means you must re-add implementations in every test (or beforeEach). restoreMocks: true ensures spyOn mocks don't leak between test files.
describe('emailService', () => {
let sendEmailSpy;
beforeEach(() => {
sendEmailSpy = jest.spyOn(emailService, 'send').mockResolvedValue(true);
});
afterEach(() => {
sendEmailSpy.mockRestore();
});
test('sends confirmation', async () => {
await processOrder(order);
expect(sendEmailSpy).toHaveBeenCalledTimes(1);
});
});Practical Assertions
Jest includes a rich set of mock-specific matchers:
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledTimes(3);
expect(mockFn).toHaveBeenCalledWith('arg1', expect.any(Number));
expect(mockFn).toHaveBeenLastCalledWith('final-arg');
expect(mockFn).toHaveBeenNthCalledWith(2, 'second-call-arg');
// Check return values
expect(mockFn).toHaveReturnedWith('expected-value');
expect(mockFn).toHaveReturnedTimes(2);expect.any(Number) and expect.objectContaining({}) are your friends when you don't care about the exact shape of every argument.
Common Pitfalls
Forgetting jest.mock() is hoisted: Writing logic inside jest.mock() that references variables from the outer scope will fail because the factory runs before variable declarations. Prefix those variables with mock — Jest hoists factories but allows variables starting with mock:
const mockSend = jest.fn();
jest.mock('./email', () => ({
send: mockSend, // ❌ ReferenceError — mockSend not yet defined at hoist time
}));
// ✅ Correct: define inside the factory or use jest.fn() directly
jest.mock('./email', () => ({
send: jest.fn(),
}));Not clearing mocks between tests: A mock with 3 calls from test 1 will show 3 + new calls in test 2. Use clearMocks: true in Jest config.
Mocking the wrong reference: If module A imports function foo from module B and you mock module B's foo, but module A already has a reference to the original foo, the mock won't intercept it. This is a common ES module issue — make sure your code always calls through the module object, or use jest.spyOn on the module's exported object.
Jest's mocking system covers the full range from lightweight function spies to complete module replacement. The key is choosing the right tool for each scenario: jest.fn() for injected dependencies, jest.spyOn() for existing objects, and jest.mock() for module-level isolation.