Full answer
Data components have four states worth testing: loading, success, error and empty. Tests should reproduce them with a controlled network, not by mocking the component's internals. If the test replaces your own useCourses hook, it proves nothing about the hook.
Network mocking. Mock Service Worker (MSW) intercepts requests at the network layer, so the real fetch code, query library and error handling run. In small tests, stubbing fetch with vi.stubGlobal or vi.fn also works, as in the example. For each test, set the response (a list, an empty list, a 500 status, a rejected promise), render, and assert.
Query rules. After render, the first state is loading: assert with getByText or a role. Data appears later: use await screen.findByRole(...) or findByText, which retry until the timeout. Failure: check for role="alert". Retry: click the button with user-event and assert the next fetch result appears. Use queryBy to assert absence.
Wrapper and isolation. Create a renderWithProviders helper that adds router, store or QueryClient providers. Create a fresh QueryClient or store for each test, with retries turned off, so tests do not share a cache and do not wait for default retry delays. Reset mocks in afterEach.
Determinism. Avoid real timers and real network. Use fake timers for debounce or polling. Do not assert on implementation details such as how many renders happened. Flaky tests usually come from shared state, missing awaits or real time.
Suite strategy. The testing pyramid, adapted: many small unit tests (pure functions, reducers, hooks with renderHook), a good number of component tests with RTL, selected integration tests at page level with mocked network, and a handful of Playwright tests for critical flows (login, checkout) against a real browser. Add accessibility checks (see the axe item), type checks and linting in CI. Keep tests close to the code, name them as behaviours, and treat a flaky test as a bug to fix or delete.
Coverage numbers are a signal, not a goal. Review which behaviours are untested.
The example stubs fetch and covers success, a failing request and retry.
import { useEffect, useState } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom/vitest';
function CourseList() {
const [attempt, setAttempt] = useState(0);
const [state, setState] = useState({ status: 'loading', courses: [], message: '' });
useEffect(() => {
let ignore = false;
setState({ status: 'loading', courses: [], message: '' });
fetch('/api/courses')
.then((response) => {
if (!response.ok) throw new Error('Request failed with status ' + response.status);
return response.json();
})
.then((courses) => {
if (!ignore) setState({ status: 'ready', courses, message: '' });
})
.catch((error) => {
if (!ignore) setState({ status: 'error', courses: [], message: error.message });
});
return () => {
ignore = true;
};
}, [attempt]);
if (state.status === 'loading') return <p>Loading courses...</p>;
if (state.status === 'error') {
return (
<div role="alert">
<p>{state.message}</p>
<button onClick={() => setAttempt((n) => n + 1)}>Retry</button>
</div>
);
}
if (state.courses.length === 0) return <p>No courses yet</p>;
return (
<ul>
{state.courses.map((course) => (
<li key={course}>{course}</li>
))}
</ul>
);
}
const jsonResponse = (body, status = 200) => Promise.resolve({ ok: status < 400, status, json: async () => body });
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
describe('CourseList', () => {
it('shows a loading message and then the courses', async () => {
vi.stubGlobal('fetch', vi.fn(() => jsonResponse(['Maths', 'Science'])));
render(<CourseList />);
expect(screen.getByText('Loading courses...')).toBeInTheDocument();
expect(await screen.findByText('Maths')).toBeInTheDocument();
expect(screen.queryByText('Loading courses...')).not.toBeInTheDocument();
});
it('shows an empty state', async () => {
vi.stubGlobal('fetch', vi.fn(() => jsonResponse([])));
render(<CourseList />);
expect(await screen.findByText('No courses yet')).toBeInTheDocument();
});
it('shows an error and recovers after retry', async () => {
const user = userEvent.setup();
const fetchMock = vi
.fn()
.mockImplementationOnce(() => jsonResponse({}, 500))
.mockImplementationOnce(() => jsonResponse(['Maths']));
vi.stubGlobal('fetch', fetchMock);
render(<CourseList />);
expect(await screen.findByRole('alert')).toHaveTextContent('Request failed with status 500');
await user.click(screen.getByRole('button', { name: 'Retry' }));
expect(await screen.findByText('Maths')).toBeInTheDocument();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});The component and tests are in one file only to keep the example complete. A real project would use Mock Service Worker and separate files. The file ran under Vitest with jsdom, and these tests passed on two consecutive runs: CourseList > shows a loading message and then the courses CourseList > shows an empty state CourseList > shows an error and recovers after retry
Key points
- Test loading, success, error, retry and empty states from the user's point of view.
- Mock at the network boundary (MSW or a fetch stub), not your own hooks.
- Use findBy queries for async content and role="alert" for errors. Use queryBy for absence.
- Fresh providers, store or QueryClient per test, with retries off, and reset mocks after each test.
- Balance unit, component, integration and end-to-end tests. Fix flaky tests.
Common mistakes
- Mocking the component's own hook, which tests nothing real.
- Using getBy for content that appears later, instead of findBy.
- Sharing a QueryClient or store between tests, so state leaks.
- Leaving default retries on and making failure tests slow.
- Asserting on implementation details such as render counts.
Follow-ups
- How does Mock Service Worker differ from stubbing fetch?
- How would you test a debounced search with fake timers?
- Which flows belong in end-to-end tests and why?
Tips
- List the four states first. It shows a systematic approach.
- Explain why mocking your own hooks is a smell.
- Mention flaky tests and how you remove their causes.