Mocking Modules and API Calls
Mock ES modules with jest.mock(), stub fetch with MSW (Mock Service Worker), and test components that depend on external data without real network calls.
Why Mock?
Unit tests should be isolated. Real API calls are slow, unreliable, and costly. Mocking replaces dependencies with controlled test doubles that return predictable responses.
jest.mock() — Mock Entire Modules
jest.mock('module-path') replaces the entire module with auto-mocked versions. All exports become jest.fn() stubs. Call mockReturnValue or mockResolvedValue to set return values.
jest.mock('./api');
import { fetchUser } from './api';
(fetchUser as jest.Mock).mockResolvedValue({ id: 1, name: 'Alice' });
test('renders user name', async () => {
render(<Profile userId="1" />);
await screen.findByText('Alice');
expect(fetchUser).toHaveBeenCalledWith('1');
});All lessons in this course
- Jest Setup and Basic Tests
- @testing-library/react: render userEvent
- @testing-library/vue: mounting components
- Mocking Modules and API Calls