Sub topic 11
Mocking callbacks, modules, and network requests
This chapter assumes you can write a basic Testing Library test, with render, screen, a getBy, findBy, or queryBy query, and user-event. It also assumes you know async/await and the basics of Jest or Vitest. Examples use Jest. Vitest differences are marked.
A mock is a stand-in for something your component depends on. Mocks let a test control inputs and observe outputs without involving the real dependency. The risk is mocking so much that the test no longer checks anything real. This chapter covers three levels of mocking, from least to most invasive.
Choosing what to mock
Mock only what sits outside the behavior you are testing. Callbacks passed in as props belong to the test. A module such as an API client, or the network itself, is something your component calls out to.
| Technique | Replaces | Fidelity | Typical use |
|---|---|---|---|
| Mock function | A callback prop | High, since the component sees an ordinary function | `onSubmit`, `onClose`, `loadUser` |
| Module mock | An imported module | Medium, since the real module never runs | API client, analytics, feature flags |
| Mock server | The network response | Highest, since `fetch` and your parsing code run for real | Data-fetching components |
Mocking callbacks with mock functions
A mock function records every call made to it, including the arguments. In Jest you create one with jest.fn(). In Vitest you use vi.fn(), imported from vitest.
Callbacks are the cheapest dependency to mock because the component already accepts them as props. Here is a small dialog component and its test:
// ConfirmDialog.jsx
export function ConfirmDialog({ message, onConfirm, onCancel }) {
return (
<div role="dialog" aria-label="Confirmation">
<p>{message}</p>
<button onClick={onCancel}>Cancel</button>
<button onClick={() => onConfirm('user-clicked')}>Delete</button>
</div>
);
}
// ConfirmDialog.test.jsx
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ConfirmDialog } from './ConfirmDialog';
test('calls onConfirm with a reason and never calls onCancel', async () => {
const user = userEvent.setup();
const onConfirm = jest.fn();
const onCancel = jest.fn();
render(<ConfirmDialog message="Delete this file?" onConfirm={onConfirm} onCancel={onCancel} />);
await user.click(screen.getByRole('button', { name: 'Delete' }));
expect(onConfirm).toHaveBeenCalledTimes(1);
expect(onConfirm).toHaveBeenCalledWith('user-clicked');
expect(onCancel).not.toHaveBeenCalled();
});The assertions use these matchers:
toHaveBeenCalledTimes(n)checks how many calls happened.toHaveBeenCalledWith(...)checks that at least one call used exactly those arguments.not.toHaveBeenCalled()checks that a callback stayed silent. This is how you test that a user action did not trigger something.
A mock function can also return values. These are the common forms:
jest.fn().mockReturnValue(42)returns a fixed value.jest.fn().mockResolvedValue(data)returns a promise that resolves withdata.jest.fn().mockRejectedValue(new Error('boom'))returns a promise that rejects.jest.fn().mockResolvedValueOnce(a).mockResolvedValueOnce(b)returns different values on successive calls.
The UserGreeting example from earlier in the tutorial uses mockResolvedValue to supply a loadUser prop. The same idea works for any function a component receives.
Mocking modules
When the component imports its dependency instead of receiving it, you can replace the whole module. Suppose a component calls an API client:
// api.js
export async function fetchUser(id) {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) throw new Error('Request failed');
return response.json();
}
// UserCard.jsx
import { useEffect, useState } from 'react';
import { fetchUser } from './api';
export function UserCard({ id }) {
const [state, setState] = useState({ status: 'loading' });
useEffect(() => {
fetchUser(id)
.then((user) => setState({ status: 'ok', user }))
.catch(() => setState({ status: 'error' }));
}, [id]);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p role="alert">Could not load user</p>;
return <h2>{state.user.name}</h2>;
}Calling jest.mock('./api') with no factory makes Jest generate an automock. Every exported function becomes a mock function that returns undefined. You then set return values per test.
// UserCard.test.jsx
import { render, screen } from '@testing-library/react';
import { UserCard } from './UserCard';
import { fetchUser } from './api';
jest.mock('./api');
afterEach(() => {
jest.clearAllMocks();
});
test('shows the user name after loading', async () => {
fetchUser.mockResolvedValue({ name: 'Ada' });
render(<UserCard id="1" />);
expect(screen.getByText('Loading...')).toBeInTheDocument();
expect(await screen.findByRole('heading', { name: 'Ada' })).toBeInTheDocument();
expect(fetchUser).toHaveBeenCalledWith('1');
});
test('shows an alert when the request fails', async () => {
fetchUser.mockRejectedValue(new Error('Request failed'));
render(<UserCard id="2" />);
expect(await screen.findByRole('alert')).toHaveTextContent('Could not load user');
});In Vitest, the shape is the same. Import vi and vi.mocked, and use vi.mock('./api'):
import { vi, test, expect } from 'vitest';
import { fetchUser } from './api';
vi.mock('./api');
test('example', async () => {
vi.mocked(fetchUser).mockResolvedValue({ name: 'Ada' });
// render and assert as above
});Hoisting and partial mocks
jest.mock and vi.mock calls are hoisted above your import statements. This lets the mock be in place before the component imports the real module. It also means a factory function cannot safely refer to variables declared in the test file. In Jest, such a variable must be named with a mock prefix.
Sometimes you want to replace one export and keep the rest. Pass a factory that spreads the real module:
jest.mock('./api', () => ({
...jest.requireActual('./api'),
fetchUser: jest.fn(),
}));In Vitest, use vi.mock('./api', async (importOriginal) => ({ ...(await importOriginal()), fetchUser: vi.fn() })).
Resetting mocks between tests
Mock state leaks between tests in the same file unless you clear it. The three reset levels differ:
| Method | Clears recorded calls | Removes implementations | Restores originals from `spyOn` |
|---|---|---|---|
| `mockClear` / `clearAllMocks` | Yes | No | No |
| `mockReset` / `resetAllMocks` | Yes | Yes | No |
| `mockRestore` / `restoreAllMocks` | Yes | Yes | Yes |
You can call these in afterEach, or set clearMocks: true in the Jest config (clearMocks: true in Vitest's test options). A leaked toHaveBeenCalledTimes(1) failure in a later test is the usual sign you forgot.
Mocking network requests with MSW
Module mocks skip your real fetch code, including URL building, status checks, and JSON parsing. A bug in api.js would pass every UserCard test above. Mock Service Worker (MSW) avoids this by intercepting requests at the network layer. The component and fetch code run unchanged, and only the response is fake.
This example uses MSW version 2 and a component that calls fetch directly:
// Profile.jsx
import { useEffect, useState } from 'react';
export function Profile() {
const [state, setState] = useState({ status: 'loading' });
useEffect(() => {
fetch('https://api.example.com/user')
.then((response) => {
if (!response.ok) throw new Error('Request failed');
return response.json();
})
.then((user) => setState({ status: 'ok', user }))
.catch(() => setState({ status: 'error' }));
}, []);
if (state.status === 'loading') return <p>Loading...</p>;
if (state.status === 'error') return <p role="alert">Could not load profile</p>;
return <h1>{state.user.name}</h1>;
}
// Profile.test.jsx
import { render, screen } from '@testing-library/react';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import { Profile } from './Profile';
const server = setupServer(
http.get('https://api.example.com/user', () => HttpResponse.json({ name: 'Ada' }))
);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('renders the user returned by the API', async () => {
render(<Profile />);
expect(await screen.findByRole('heading', { name: 'Ada' })).toBeInTheDocument();
});
test('renders an error when the server responds with 500', async () => {
server.use(
http.get('https://api.example.com/user', () => new HttpResponse(null, { status: 500 }))
);
render(<Profile />);
expect(await screen.findByRole('alert')).toHaveTextContent('Could not load profile');
});The setup has four parts:
setupServertakes default handlers that describe the happy path.listen,resetHandlers, andcloserun in the standard lifecycle hooks.resetHandlersremoves per-test overrides so one test's failure scenario does not leak into the next.server.useadds a handler for a single test. This is how you test errors, empty lists, and slow responses.onUnhandledRequest: 'error'makes a request with no matching handler fail the test. Without it, MSW only prints a warning, and a typo in a URL can pass silently.
Use absolute URLs in handlers and in the code under test. In a Node test process, a relative URL such as /user has no base to resolve against.
What not to mock
Every mock removes some real behavior from the test, so keep the following in mind:
- Do not mock React, your own child components, or hooks such as
useState. Mocking a child component means the test no longer checks that the parent integrates with it. - Do not assert on the internals of a module mock beyond what matters to the user. Checking that
fetchUserwas called with'1'is reasonable because it is the contract. Checking the exact number of renders is not. - Prefer mock functions for props, MSW for network calls, and module mocks for things that are hard to run in tests, such as analytics, timers, or browser-only APIs.
- Keep mock data realistic. A fixture that is missing a field the real API always returns can hide a bug or cause a false failure.
Exercise
A test mocks ./api with jest.mock('./api') and sets fetchUser.mockResolvedValue({ name: 'Ada' }) in the first test. The second test in the same file expects fetchUser to have been called once, but it fails with "called 2 times". What is the cause, and what is the fix?
Show answer
Mock call records persist across tests in a file, so the call from the first test is still counted. Clear them between tests with afterEach(() => jest.clearAllMocks()), or set clearMocks: true in the Jest config. Use resetAllMocks instead if you also want implementations such as mockResolvedValue removed.
Exercise
Why might a component test pass with jest.mock('./api') even though api.js has a bug in how it parses the response, and which technique would catch the bug?
Show answer
The module mock replaces api.js entirely, so its real parsing code never runs. Mocking the network with MSW instead keeps api.js and fetch real, so a parsing bug produces a wrong value or an error that the test can see.