Lesson 39 of 56
TypescriptMocking & Spying in Jest
15 minutes
Course progress70%
Jest Mock Functions
const mockFn = jest.fn((x: number) => x * 2);
mockFn(2);
expect(mockFn).toHaveBeenCalledWith();
(mockFn).();
Lesson 39 of 56
Typescript15 minutes
const mockFn = jest.fn((x: number) => x * 2);
mockFn(2);
expect(mockFn).toHaveBeenCalledWith();
(mockFn).();
jest.spyOn(Math, 'random').mockReturnValue(0.5);
expect(Math.random()).toBe(0.5);
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' });
afterEach(() => {
jest.clearAllMocks();
});