Jest provides jest.fn() for mock functions, jest.mock() for modules, and jest.spyOn() for spying on methods. For API calls, mock fetch/axios or use libraries like MSW. Mocks isolate code under test and allow controlling dependencies.
Mock Types:
jest.fn(): Create mock function
jest.mock(): Mock entire module
jest.spyOn(): Spy on existing method
API Mocking:
describe('Mock functions', () => {
test('basic mock function', () => {
const mockFn = jest.fn();
mockFn('hello');
mockFn('world');
expect(mockFn).toHaveBeenCalledTimes(2);
expect(mockFn).toHaveBeenCalledWith('hello');
expect(mockFn).toHaveBeenLastCalledWith('world');
});
test('mock with return value', () => {
const mockFn = jest.fn()
.mockReturnValue('default')
.mockReturnValueOnce('first')
.mockReturnValueOnce('second');
expect(mockFn()).toBe('first');
expect(mockFn()).toBe('second');
expect(mockFn()).toBe('default');
});
test('mock with implementation', () => {
const mockFn = jest.fn((x) => x * 2);
expect(mockFn(5)).toBe(10);
expect(mockFn).toHaveBeenCalledWith(5);
});
test('mock async function', async () => {
const mockFn = jest.fn().mockResolvedValue({ id: 1, name: 'Alice' });
const result = await mockFn();
expect(result.name).toBe('Alice');
});
});