Partial Module Mocks with requireActual
You'll learn how to mock just the parts of a module you want to control while keeping the original functionality for everything else.
The Problem with Full Module Mocks
When you use jest.mock() on a module, Jest replaces everything that module exports with mock implementations. But sometimes you only want to mock one or two functions while keeping the rest of the module's real behavior intact. That's where partial mocking comes in.
Using requireActual to Keep the Real Stuff
jest.requireActual() fetches the original, unmocked version of a module. You can combine it with jest.mock() to create a hybrid: real implementations for most exports, with only specific functions mocked.
// userService.js exports: { getUser, saveUser, deleteUser }
jest.mock('./userService', () => {
const actualModule = jest.requireActual('./userService');
return {
...actualModule, // Keep all real implementations
saveUser: jest.fn() // Only mock saveUser
};
});
// In your test
test('saveUser is mocked, others are real', () => {
const { getUser, saveUser } = require('./userService');
saveUser({ id: 1, name: 'Alice' });
expect(saveUser).toHaveBeenCalled(); // Mock tracked the call
// getUser still runs the actual implementation
const user = getUser(1); // Real database query happens
});
When This Pattern Shines
This is invaluable when testing code that calls multiple functions from the same module—you mock the side-effect-heavy operations (like database writes) while allowing pure logic functions to run normally. Think of it like replacing just one actor in a play while keeping the rest of the cast.
Key Takeaway: Use jest.requireActual() inside jest.mock() to selectively override only the exports you need to control, preserving the rest of the module's authentic behavior.