Jest Mocking
Mocking functions, modules, and APIs in Jest.
Mock Functions
Create mock
const mockFn = jest.fn();
With return value
const mockFn = jest.fn(() => 42);
Mock implementation
mockFn.mockImplementation(() => true);
Mock return value
mockFn.mockReturnValue("hello");
mockFn.mockReturnValueOnce("first");
Mock Assertions
Called checks
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledTimes(2);
expect(mockFn).toHaveBeenCalledWith(arg1, arg2);
expect(mockFn).toHaveBeenLastCalledWith(arg);
Return value
expect(mockFn).toHaveReturnedWith(42);
Module Mocking
Mock entire module
jest.mock("./module");
Mock with factory
jest.mock("axios", () => ({
get: jest.fn(() => Promise.resolve({ data: {} }))
}));
Partial mock
jest.mock("./utils", () => ({
...jest.requireActual("./utils"),
someFunc: jest.fn()
}));
Timers & Async
Mock timers
jest.useFakeTimers();
Fast-forward time
jest.advanceTimersByTime(1000);
jest.runAllTimers();
Clear mocks
jest.clearAllMocks();
jest.resetAllMocks();
jest.restoreAllMocks();