Mocking
Mock functions, modules, and partial implementations with jest.fn and jest.mock.
Mock Functions
jest.fn() creates callable mocks tracking calls, arguments, and return values. mockReturnValue, mockResolvedValue, and mockImplementation configure behavior.
Mocks replace dependencies in unit tests so you test one module in isolation without network, filesystem, or database side effects.
const sendEmail = jest.fn().mockResolvedValue({ sent: true });
await notifyUser(user, sendEmail);
expect(sendEmail).toHaveBeenCalledWith(user.email);Module Mocks
jest.mock("module-path") hoists to top of file and replaces entire module with automatic mock or factory. Factory receives actual module for selective replacement.
Mock modules before importing the system under test. Use jest.unmock or jest.requireActual for integration-style tests needing real implementations.
jest.mock("./api", () => ({
fetchUser: jest.fn(),
}));
import { fetchUser } from "./api";
import { loadProfile } from "./profile";Partial Mocks
jest.requireActual combined with spread preserves real module exports while overriding specific functions. Useful when only one export needs mocking.
Avoid over-mocking—if everything is mocked, you test mocks not code. Mock at system boundaries (HTTP, DB, clock).
- Clear mocks in beforeEach with jest.clearAllMocks()
- jest.resetModules() when test order affects module cache
- Manual __mocks__ folder provides default mocks for module name
jest.mock("./utils", () => ({
...jest.requireActual("./utils"),
generateId: jest.fn(() => "fixed-id"),
}));jest.mock Patterns
Mock ES modules and CommonJS consistently per project module system. Virtual mocks mock modules not present in node_modules.
For class constructors, mockImplementation returns instances with controlled methods.
jest.mock("axios");
import axios from "axios";
const mockedAxios = axios as jest.Mocked<typeof axios>;
mockedAxios.get.mockResolvedValue({ data: { id: 1 } });When Not to Mock
Prefer real implementations for pure functions and value objects. Use test doubles only at IO boundaries. Integration tests with real database containers catch mock drift.
Document mock assumptions—if mock behavior diverges from production API, tests give false confidence.
- Use MSW to mock HTTP at network layer for realistic fetch tests
- Inject dependencies via parameters for easier testing without module mocks
- Verify mock call counts sparingly—focus on outcomes