React Testing with Vitest, Testing Library and MSW
On this page
Learning Objective
Test React components by their user-visible behavior with Vitest and Testing Library, mock the network with Mock Service Worker so tests exercise the real fetch and query code, test states, forms and errors, add accessibility and hostile-content checks, and keep mocks aligned with the real API contract.
Concept Explanation
Component tests should describe what a user sees and does, not how the component is built. Testing Library's guiding principle is that the more your tests resemble how the software is used, the more confidence they give. In practice that means finding elements the way users and assistive technology do, by role, label, and visible text, instead of by CSS class or component internals, and interacting through realistic events such as typing and clicking with the userEvent library. A test that finds a button by its accessible name and clicks it survives refactoring, while a test that reaches into state or class names breaks whenever the implementation changes without any change in behavior.
Vitest is the test runner that fits a Vite project: it reuses your Vite configuration, starts fast, and offers a Jest-compatible API, with jsdom providing a simulated browser environment. Testing components that fetch data raises the question of how to fake the network. Mocking the fetch function or your API client function tests only that you called the mock. Mock Service Worker, MSW, intercepts requests at the network layer instead, so the real fetch wrapper, Zod parsing, TanStack Query caching, and error handling all run, and only the server is simulated. You declare handlers for the requests you expect, and configure it to fail the test on any unhandled request, which catches components that call endpoints you did not anticipate.
Testing components that use TanStack Query needs a fresh QueryClient for every test, with retries turned off so failures show immediately instead of after several delayed attempts, and a shared render helper that wraps components in the providers they need: query client, router, and any auth context. Then write tests for each state that Day 57 identified: loading, success, empty, and each class of error. Test the flows that matter: submitting a form, seeing a server validation message beside the right field, an optimistic update rolling back on a conflict, and a 401 sending the user to sign in. These are the behaviors that break during changes to the client and the ones users notice.
Two kinds of tests deserve special attention for a full-stack developer. Accessibility checks with vitest-axe, built on the axe-core engine, catch a class of problems automatically, such as unlabeled inputs and invalid ARIA, though they cannot replace manual testing. Security tests feed hostile content through components and assert that it is rendered inert: script tags and event handler attributes displayed as text, unsafe URLs not turned into links. Finally, keep mocks honest. If your MSW handlers return hand-written JSON, they can drift from the real API and give false confidence. Type the handlers with the OpenAPI-generated types, using a tool like openapi-msw, or validate the mock bodies with the same Zod schemas the client uses, so a contract change breaks the tests instead of production.
| Concern | Approach | Note |
|---|---|---|
| Finding elements | By role, label and text | Matches how users and assistive tech see the page |
| Interaction | userEvent, not fireEvent | Realistic typing, clicking and focus |
| Network | MSW at the network boundary | Real fetch, parsing and caching run |
| Query state | New QueryClient per test, retries off | Isolated and immediate failures |
| Accessibility | vitest-axe on rendered output | Automated baseline, not a replacement for manual checks |
| Mock accuracy | Typed from OpenAPI or checked with Zod | Prevents mocks drifting from the API |
Worked Example: Setup, a Provider Helper, State Tests, an Accessibility Check and a Hostile Payload
The setup file starts the mock server. The helper wraps components. The tests cover loading, empty, error, success, and a rollback, plus accessibility and XSS checks.
// vitest.config.ts
export default defineConfig({
plugins: [react()],
test: { environment: 'jsdom', setupFiles: './src/test/setup.ts', globals: true },
});
// src/test/setup.ts
import '@testing-library/jest-dom/vitest';
import { afterAll, afterEach, beforeAll } from 'vitest';
import { server } from './server';
import { cleanup } from '@testing-library/react';
import * as matchers from 'vitest-axe/matchers';
expect.extend(matchers);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); // an unexpected request fails the test
afterEach(() => { server.resetHandlers(); cleanup(); });
afterAll(() => server.close());
// src/test/server.ts
import { setupServer } from 'msw/node';
export const server = setupServer();// src/test/render.tsx: every test gets isolated providers and a clean cache.
export function renderWithProviders(ui: ReactElement, { route = '/' } = {}) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
return {
user: userEvent.setup(),
...render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[route]}>{ui}</MemoryRouter>
</QueryClientProvider>,
),
};
}
// Typed factory: a fake note that always satisfies the real contract.
export const aNote = (over: Partial<Note> = {}): Note =>
NoteSchema.parse({ id: 1, title: 'Write report', body: null, status: 'todo', updatedAt: '2026-09-01T09:00:00Z', ...over });// src/features/board/Board.test.tsx
const tasks = (list: Note[]) => http.get('/api/projects/p1/tasks', () => HttpResponse.json({ items: list, nextCursor: null }));
it('shows a skeleton first and then the tasks', async () => {
server.use(tasks([aNote({ title: 'Write report' })]));
renderWithProviders(<Board projectId="p1" />);
expect(screen.getByRole('status', { name: /loading board/i })).toBeInTheDocument();
expect(await screen.findByText('Write report')).toBeVisible();
});
it('explains what to do when the board is empty', async () => {
server.use(tasks([]));
renderWithProviders(<Board projectId="p1" />);
expect(await screen.findByText(/no tasks yet/i)).toBeVisible();
});
it('shows a friendly message and a reference id when the server fails', async () => {
server.use(http.get('/api/projects/p1/tasks', () =>
HttpResponse.json({ status: 500, title: 'Boom', traceId: 'abc-123', detail: 'System.NullReferenceException at Foo.Bar()' }, { status: 500 })));
renderWithProviders(<Board projectId="p1" />);
expect(await screen.findByText(/something went wrong on our side/i)).toBeVisible();
expect(screen.getByText(/abc-123/)).toBeVisible();
expect(screen.queryByText(/NullReferenceException/)).not.toBeInTheDocument(); // internals never reach the screen
});
it('moves a task and rolls back when the server reports a conflict', async () => {
server.use(tasks([aNote({ title: 'Write report', status: 'todo' })]),
http.patch('/api/tasks/:id/status', () => HttpResponse.json({ status: 412, title: 'Changed' }, { status: 412 })));
const { user } = renderWithProviders(<Board projectId="p1" />);
const select = await screen.findByLabelText('Move Write report');
await user.selectOptions(select, 'done');
expect(await screen.findByText(/changed while you were working/i)).toBeVisible();
expect(select).toHaveValue('todo');
});
it('has no detectable accessibility violations', async () => {
server.use(tasks([aNote()]));
const { container } = renderWithProviders(<Board projectId="p1" />);
await screen.findByText('Write report');
expect(await axe(container)).toHaveNoViolations();
});
it.each(['<img src=x onerror=alert(1)>', '<script>alert(1)</script>', 'javascript:alert(1)'])(
'renders hostile titles as inert text: %s', async (payload) => {
server.use(tasks([aNote({ title: payload })]));
const { container } = renderWithProviders(<Board projectId="p1" />);
expect(await screen.findByText(payload)).toBeVisible(); // visible as literal text
expect(container.querySelector('img, script')).toBeNull(); // and never turned into elements
});Because onUnhandledRequest is set to error, a component that quietly calls an endpoint the test did not anticipate fails loudly, which keeps the mocked surface honest. Pair this with the contract check from Day 30 so handlers built from generated types cannot drift from the server.
Real-World Examples
- Testing Library was created by Kent C. Dodds in 2018, first as DOM Testing Library and then with React bindings, as a reaction to enzyme-style tests that asserted on component internals and broke on refactors. Its guiding principle of querying the way users find elements has been adopted across frameworks, and it is now the most widely recommended approach for testing React components.
- Mock Service Worker, created by Artem Zakharchenko, popularized intercepting requests at the network layer with the same handlers usable in tests, Storybook, and the browser during development. Because the application code is unchanged and only the server is simulated, teams get high-fidelity component tests without spinning up a backend.
Review Questions & Answers
MSW intercepts at the network boundary, so your real client code, response parsing, caching, and error handling all execute, and only the server is faked. Mocking the client function only verifies that your component called it, skipping everything that commonly breaks between the component and the network.
A shared client would carry cached data from one test into the next, creating order-dependent failures. Default retries delay error states by several backoff intervals, making failure tests slow or time out. A fresh client with retries off gives isolation and immediate, deterministic results.
It fails the test when the component makes a request no handler was written for, which reveals unintended API calls and prevents tests from silently passing while relying on real network access or incomplete mocks. It keeps the declared mock surface identical to what the component actually uses.
If the mock JSON drifts from the real API shape, the component tests pass against data the server never sends, and the bug appears only in production. Building mocks with the generated OpenAPI types or parsing them with the same Zod schemas as the client makes any contract change break the tests immediately.