Lesson 39 of 56 · Typescript
Mocking & Spying in Jest
Duration: 15 minutes
Jest Mock Functions
const mockFn = jest.fn((x: number) => x * 2);
mockFn(2);
expect(mockFn).toHaveBeenCalledWith(2);
expect(mockFn).toHaveReturnedWith(4);
Manual Mock Implementation
jest.spyOn(Math, 'random').mockReturnValue(0.5);
expect(Math.random()).toBe(0.5);
Auto‑mocking a module
jest.mock('../src/api'); // creates a mock based on the module’s shape
import { fetchUser } from '../src/api';
(fetchUser as jest.Mock).mockResolvedValue({ id: 1, name: 'Bob' });
Resetting mocks
afterEach(() => {
jest.clearAllMocks();
});