Sub topic 11
Mocking callbacks, modules, and network requests
This chapter assumes you can write a basic Testing Library test with render, screen, and user-event, and that you know Jest or Vitest syntax. Examples use jest. In Vitest, use vi in place of jest.
Why mock at all
A component test should cover the component, not the services behind it. Real network calls are slow and flaky, and they make results depend on data you don't control. A mock replaces one dependency with a controlled stand-in. You choose the level at which to replace it.
Mocking callbacks
When a component receives a function as a prop, pass jest.fn() and assert on how it was called. You saw this with LoginForm:
const handleSubmit = jest.fn();
render(<LoginForm onSubmit={handleSubmit} />);
// ...interact...
expect(handleSubmit).toHaveBeenCalledWith({ email: '[email protected]' });Useful matchers are toHaveBeenCalledTimes(n), toHaveBeenCalledWith(...), and not.toHaveBeenCalled(). Use mockResolvedValue or mockRejectedValue when the callback returns a promise, as loadUser did in the async chapter.
Mocking modules
Sometimes a component imports its dependency directly. jest.mock replaces the whole module for the test file. Jest hoists the call above your imports, so the component receives the mocked version.
// api.js
export async function fetchUser(id) {
const res = await fetch(`https://api.example.com/users/${id}`);
return res.json();
}
// UserCard.jsx
import { useEffect, useState } from 'react';
import { fetchUser } from './api';
export function UserCard({ id }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(id).then(setUser);
}, [id]);
return user ? <h2>{user.name}</h2> : <p>Loading...</p>;
}
// UserCard.test.jsx
import { render, screen } from '@testing-library/react';
import { UserCard } from './UserCard';
import { fetchUser } from './api';
jest.mock('./api');
test('shows the fetched user', async () => {
jest.mocked(fetchUser).mockResolvedValue({ name: 'Ada' });
render(<UserCard id={1} />);
expect(await screen.findByRole('heading', { name: 'Ada' })).toBeInTheDocument();
expect(fetchUser).toHaveBeenCalledWith(1);
});With automock, every export becomes a jest.fn() that returns undefined. Set a return value in each test that needs one. In Vitest, vi.mock is also hoisted, and you wrap the mocked import with vi.mocked.
Mocking network requests
Mocking fetch or axios ties your test to how the code makes requests. Mock Service Worker (MSW) intercepts requests at the network level instead. The component and api.js run unchanged, and your test only describes the server's responses.
// UserCard.msw.test.jsx
import { render, screen } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { UserCard } from './UserCard';
const server = setupServer(
http.get('https://api.example.com/users/1', () =>
HttpResponse.json({ name: 'Ada' })
)
);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('renders the user returned by the server', async () => {
render(<UserCard id={1} />);
expect(await screen.findByRole('heading', { name: 'Ada' })).toBeInTheDocument();
});
test('can override the response for one test', async () => {
server.use(
http.get('https://api.example.com/users/1', () =>
HttpResponse.json({ name: 'Grace' })
)
);
render(<UserCard id={1} />);
expect(await screen.findByRole('heading', { name: 'Grace' })).toBeInTheDocument();
});resetHandlers after each test removes per-test overrides, so tests stay independent. onUnhandledRequest: 'error' makes a forgotten handler fail loudly.
Common mistakes
- Forgetting to reset mocks. Call
jest.clearAllMocks()inafterEach, or setclearMocks: truein the Jest config, so call counts don't leak between tests. - Mocking too much. If you mock every child component and hook, the test no longer shows whether the screen works for a user.
- Asserting on a mock instead of the UI. Prefer checking what the user sees. Assert on a mock when the call is the behavior, such as a submit callback.
Exercise
A component calls fetchUser imported from ./api. You want the test to cover the real fetchUser code as well. Should you use jest.mock('./api') or an MSW handler, and why?
Show answer
Use an MSW handler. jest.mock('./api') replaces fetchUser entirely, so its real code never runs. MSW intercepts the HTTP request, so the component and fetchUser both run as in production, and only the server response is faked.