React · Lesson 7
Testing & architecture
React Testing Library the way it's meant to be used (behaviour, roles, user-event), mocking the network with MSW, feature folders and where state lives, React Router data routers (loaders, actions, nested routes), and error and Suspense boundaries.
In short
- Test behaviour with roles, names and
user-event findByfor async;queryByonly for absence- Mock the network with MSW, not your own code
- Feature folders with a public
index.ts - Route loaders in parallel; boundaries per region
A React codebase stays pleasant when two things hold: the tests check what users see, so you can refactor without rewriting them, and the structure keeps features apart, so a change in orders doesn't break invoices. This topic covers the tools and habits behind both: React Testing Library and MSW for tests, feature folders and state placement for structure, React Router's data routers for pages and their data, and boundaries for loading and failure states.
React, Testing Library, MSW and React Router can't run in the lab, so their snippets have no ▶ Try button. Plain
TypeScript snippets do, and the exercises rebuild the mechanisms: role queries, path matching, waitFor, a mock
server, an import-boundary checker, a data router and a renderer with error and Suspense boundaries.
Test behaviour, not implementation
The more your tests resemble the way your software is used, the more confidence they can give you. (the guiding principle of Testing Library)
A user doesn't know your component has a useState called isOpen. They see a button called "Add line", click it,
and see a new row. Test that:
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import { OrderForm } from './OrderForm';
test('adds a line and shows the new total', async () => {
const user = userEvent.setup();
render(<OrderForm />);
await user.type(screen.getByRole('textbox', { name: 'Product' }), 'Keyboard');
await user.type(screen.getByRole('spinbutton', { name: 'Quantity' }), '2');
await user.click(screen.getByRole('button', { name: 'Add line' }));
expect(screen.getByRole('row', { name: /keyboard/i })).toBeInTheDocument();
expect(screen.getByText('Total: 2 items')).toBeInTheDocument();
});
- Query like a user. In order of preference:
getByRole(withname),getByLabelText,getByPlaceholderText,getByText,getByDisplayValue,getByAltText,getByTitle, andgetByTestIdas a last resort. Role queries double as an accessibility check: an input without a label can't be found by its name. - Pick the variant by what you expect.
getBywhen it must be there (throws otherwise, with a readable dump of the DOM),queryByonly to assert absence,findByfor something that appears after an async update, and theAllversions for several matches. Exercise 1 builds them. user-event, notfireEvent.userEvent.setup()thenawait user.click(...)/await user.type(...)plays the whole sequence a browser does (pointer events, focus, key events, input events), and refuses to click a disabled button.fireEventdispatches one event and skips all of that. Alwaysawaituser-event calls.- Wait for async results with
findBy...,waitFor(retry an assertion until it passes) andwaitForElementToBeRemoved. Exercise 3 builds them, and explains why the last error is what you see on failure. - What not to test: state values, hook internals, which child component was rendered, CSS class names, or big snapshot files nobody reads. Those tests break on every refactor and catch few bugs.
- Hooks with real logic can be tested on their own with
renderHook(() => useCart()). Often it's simpler to test the component that uses them.
Most components need providers (a query client, a router, a theme). Put them in one helper so every test renders the same way:
import type { ReactElement } from 'react';
import { render } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { createMemoryRouter, RouterProvider } from 'react-router';
export function renderWithProviders(ui: ReactElement, { route = '/' } = {}) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); // fail fast in tests
const router = createMemoryRouter([{ path: '*', element: ui }], { initialEntries: [route] });
return render(
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>,
);
}
A new QueryClient per test keeps cached data from leaking between tests, and retry: false stops a failing
request from being retried three times (with back-off) before your error state appears.
Mocking the network with MSW
Mock Service Worker intercepts requests at the network level. Your components, hooks, fetch wrapper and query
cache all run for real; only the server is fake:
// src/test/handlers.ts
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('/api/orders', () => HttpResponse.json([{ id: 'A-1', customer: 'Example', total: 120 }])),
http.get('/api/orders/:orderId', ({ params }) =>
params.orderId === 'A-1' ? HttpResponse.json({ id: 'A-1', lines: [] }) : HttpResponse.json({ title: 'Not found' }, { status: 404 }),
),
http.post('/api/orders', async ({ request }) => {
const draft = (await request.json()) as { customer: string };
return HttpResponse.json({ id: 'A-2', ...draft }, { status: 201 });
}),
];
// src/test/setup.ts (Vitest setupFiles)
import { afterAll, afterEach, beforeAll } from 'vitest';
import { setupServer } from 'msw/node';
import { handlers } from './handlers';
export const server = setupServer(...handlers);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' })); // a forgotten handler fails the test
afterEach(() => server.resetHandlers()); // drop per-test overrides
afterAll(() => server.close());
import { http, HttpResponse } from 'msw';
import { screen } from '@testing-library/react';
import { test, expect } from 'vitest';
import { server } from './test/setup';
import { renderWithProviders } from './test/render';
import { OrderList } from './features/orders';
test('shows an error when the orders API is down', async () => {
server.use(http.get('/api/orders', () => HttpResponse.json({ title: 'Unavailable' }, { status: 503 })));
renderWithProviders(<OrderList />);
expect(await screen.findByRole('alert')).toHaveTextContent('Orders are unavailable');
});
- Happy path in the shared handlers, edge cases per test with
server.use(...): a503, an empty list, a slow response (await delay(500)in the handler), a dropped connection (HttpResponse.error()). - HTTP errors are responses, not rejections.
fetchresolves for a404or503withresponse.ok === false, and only rejects when the network fails. Your API layer must checkok:
const created = Response.json({ id: 'A-2' }, { status: 201 });
const missing = new Response('Not found', { status: 404 });
console.log(created.status, created.ok, created.headers.get('content-type'));
console.log(missing.status, missing.ok); // fetch would resolve with this, not reject
- The same handlers can run in the browser through a Service Worker, for local development before the backend exists and for Storybook.
Exercise 4 builds the matching, overrides, once handlers and network errors.
Folders, components and where state lives
Organise by feature, not by file type. A components/, hooks/, services/ split scatters one feature across
the whole tree; a feature folder keeps it together and gives it a public API:
src/
app/ routes, providers, the layout shell
features/
orders/
index.ts the public API: export { OrderList, OrderPage, useOrders, type Order }
api.ts fetch functions + query keys
useOrders.ts
OrderList.tsx
OrderList.test.tsx tests live next to the code
customers/
shared/
ui/ Button, Table, Dialog: no business logic
api/client.ts fetch wrapper: base URL, auth token, error mapping
- Features import shared code, and other features only through their
index.ts. Shared code never imports features. Lint rules (eslint-plugin-boundaries, dependency-cruiser, Nx module boundaries) enforce it in CI; exercise 5 builds that check. - Container and presentational: the old pattern of a container component that fetches and a presentational one
that renders props lives on as a custom hook plus a component.
useOrders()owns data and effects;<OrderTable orders={...} onSelect={...} />only renders, so it's trivial to test and to show in Storybook. - Colocate state. Keep state in the lowest component that needs it, and lift it only when siblings need to share it. Where state should live, in order:
| Kind of state | Where |
|---|---|
| UI state of one component (open, hovered, draft text) | useState in that component |
| Shared by a few nearby components | lifted to their closest common parent |
| Server data | a query cache (TanStack Query), never copied into state |
| Filters, sorting, paging, the selected tab | the URL (useSearchParams): shareable, survives refresh, back button works |
| App-wide client state (theme, the signed-in user's preferences) | context, or a small store (Zustand, Redux Toolkit) |
Routing: React Router data routers
React Router 7 can run as a plain library (<BrowserRouter> and <Routes>), in data mode
(createBrowserRouter), or as a full framework. Data mode moves data loading out of components and into routes:
import { createBrowserRouter, Form, Outlet, redirect, RouterProvider, useLoaderData, useNavigation, useRouteError } from 'react-router';
import { api } from './shared/api';
const router = createBrowserRouter([
{
path: '/',
Component: AppLayout,
ErrorBoundary: AppError, // nothing ever goes blank
loader: async () => {
const user = await api.me();
if (!user) throw redirect('/login'); // an auth guard, before anything renders
return { user };
},
children: [
{ index: true, Component: Dashboard },
{
path: 'orders',
lazy: () => import('./features/orders/routes'), // code-split: loaded on first visit
},
{
path: 'orders/:orderId',
Component: OrderPage,
ErrorBoundary: OrderError,
loader: ({ params }) => api.order(params.orderId!),
action: async ({ request, params }) => {
const form = await request.formData();
await api.updateOrder(params.orderId!, { note: String(form.get('note')) });
return null; // after an action, the page's loaders run again
},
},
],
},
{ path: '/login', Component: Login },
]);
function AppLayout() {
const { user } = useLoaderData() as { user: { name: string } };
const navigation = useNavigation(); // 'idle' | 'loading' | 'submitting'
return (
<>
<header>Signed in as {user.name}</header>
{navigation.state === 'loading' && <progress />}
<Outlet /> {/* the matched child route renders here */}
</>
);
}
function OrderPage() {
const order = useLoaderData() as { id: string; note: string };
return (
<Form method="post">
<h1>Order {order.id}</h1>
<textarea name="note" defaultValue={order.note} />
<button>Save</button>
</Form>
);
}
function OrderError() {
const error = useRouteError();
return <p role="alert">Could not load this order. {error instanceof Error ? error.message : ''}</p>;
}
// createRoot(el).render(<RouterProvider router={router} />)
- Nested routes match from the top down. Each parent renders an
<Outlet />where its matched child goes, so layouts nest naturally. Index routes render at the parent's own URL. - Loaders run in parallel for every matched route, before rendering, which removes the fetch-on-render
waterfall. They get
paramsand arequest(with an abort signal, so a navigation away cancels them). - Actions handle
<Form method="post">submissions (anduseFetcherfor updates that don't navigate), then React Router revalidates the loaders, so the page shows fresh data without manual refetching. throw redirect(...)in a loader is the guard pattern: protected pages never render, not even for one frame.- Errors bubble to the nearest route
ErrorBoundary, and the parent layouts above it keep working. - Ranking: static segments beat dynamic ones (
/orders/newbeats/orders/:orderId), whatever the order you define them in. - With TanStack Query, loaders and the cache work together:
loader: () => queryClient.ensureQueryData(ordersQuery)starts the request early, and the component reads the same data withuseQuery. - Testing routes:
createMemoryRouter(routes, { initialEntries: ['/orders/A-1'] })renders the real route config in a test, loaders and all, with MSW answering the requests.
Exercise 2 matches paths; exercise 6 builds the data router's navigation: ranking, parallel loaders, redirects and error bubbling.
Error boundaries and Suspense boundaries
Rendering can end in two non-happy ways, and each has its own boundary:
- a component throws an error: the nearest error boundary renders its fallback instead of its subtree;
- a component suspends (it reads data that isn't ready yet, with
use(promise),lazy(), or a Suspense-enabled query): the nearest<Suspense>renders its fallback until the data is ready.
import { lazy, Suspense, use } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
const ReportsChart = lazy(() => import('./ReportsChart')); // the chart's code is loaded on first render
function Orders({ ordersPromise }: { ordersPromise: Promise<Order[]> }) {
const orders = use(ordersPromise); // suspends until the promise settles; throws if it rejects
return <OrderTable orders={orders} />;
}
export function Dashboard({ ordersPromise }: { ordersPromise: Promise<Order[]> }) {
return (
<>
<ErrorBoundary fallback={<p role="alert">Orders are unavailable right now.</p>}>
<Suspense fallback={<TableSkeleton />}>
<Orders ordersPromise={ordersPromise} />
</Suspense>
</ErrorBoundary>
<ErrorBoundary fallbackRender={({ resetErrorBoundary }) => <button onClick={resetErrorBoundary}>Retry chart</button>}>
<Suspense fallback={<ChartSkeleton />}>
<ReportsChart />
</Suspense>
</ErrorBoundary>
</>
);
}
- An error boundary is a class component with
static getDerivedStateFromError(and usuallycomponentDidCatchto log). Most teams usereact-error-boundary, which addsfallbackRender,resetErrorBoundaryandresetKeys(reset when, say, the route changes). - Error boundaries catch errors thrown while rendering (and in lifecycles and effects) below them. They don't
catch errors in event handlers, timers or promise callbacks: handle those with
try/catchand state, or rethrow them into rendering. The exception is a transition: an error thrown insidestartTransition(fromuseTransition) or in auseActionStateaction does reach the nearest error boundary. - Placement is a design decision. One boundary near the root so the app never goes blank, then one per independent region, so a broken chart doesn't take the orders table with it. Suspense boundaries go where a loading state makes sense to the user: too many, and the page pops in piece by piece.
- Never create the promise during render for
use(): a new promise every render means a new request every render and a component that never stops suspending. Create it in a loader, an event handler or a cache, and pass it down. - Updates inside
startTransition(and router navigations) that suspend keep the current screen instead of flashing a fallback. - React 19 reports errors at the root:
createRoot(el, { onCaughtError, onUncaughtError })is the single place to send them to your telemetry (Amazon CloudWatch, Azure Application Insights, Google Cloud Error Reporting, Sentry).
How the two kinds pass through each other is easiest to see in code. Here are the rules as a tiny renderer:
type Child = { name: string; throws?: 'error' | 'suspend' } | { boundary: 'error' | 'suspense'; fallback: string; children: Child[] };
function render(node: Child): string[] {
if ('name' in node) {
if (node.throws === 'error') throw new Error(`${node.name} failed`);
if (node.throws === 'suspend') throw Promise.resolve();
return [node.name];
}
try {
return node.children.flatMap(render);
} catch (e) {
const suspended = e instanceof Promise;
if ((node.boundary === 'suspense') !== suspended) throw e; // not my kind: pass it up
return [node.fallback];
}
}
const page: Child = {
boundary: 'error',
fallback: 'Something went wrong',
children: [
{ name: 'Header' },
{ boundary: 'suspense', fallback: 'Loading orders...', children: [{ name: 'Orders', throws: 'suspend' }] },
{ name: 'Footer' },
],
};
console.log(render(page)); // the Suspense boundary catches the promise
const broken: Child = {
...page,
children: [{ name: 'Header' }, { boundary: 'suspense', fallback: 'Loading orders...', children: [{ name: 'Orders', throws: 'error' }] }],
};
console.log(render(broken)); // the error passes through Suspense to the error boundary
Exercise 7 builds the full version, with component stacks for error reporting and a promise cache for use().
Common mistakes
- Testing implementation details: state, props passed to children, class names, snapshot files of whole pages.
getByTestIdeverywhere instead of roles and labels, which hides accessibility problems.fireEventinstead ofuser-event, or a user-event call withoutawait.waitForaround agetBy(usefindBy), or side effects inside awaitForcallback.- Mocking
fetchor your own hooks withvi.mockin every test instead of describing the API once with MSW. - Sharing one
QueryClientbetween tests, or leaving retries on. - Feature code reaching into another feature's internals, and shared code importing features.
- Server data copied into global state, and filters kept in state instead of the URL.
- Fetching in effects inside nested routes (a waterfall) instead of route loaders.
- No error boundary at all (a blank page on the first bug), or a single one for the whole app.
In a real codebase
Side note
- Vitest + React Testing Library + user-event + jest-dom + MSW for component and integration tests, with a
renderWithProvidershelper, and Playwright for a handful of end-to-end journeys against a real backend (sign-in, create an order, pay). - MSW handlers that mirror the ASP.NET Core API contract (often generated from its OpenAPI document), used by tests, Storybook and local development alike.
- Feature folders with
index.tspublic APIs, enforced by lint rules in CI, and tests next to the code. - A route config with loaders that prime the query cache, route-level error boundaries, lazy routes for code splitting, and an auth guard in the root loader (the OIDC client library gets a token silently before the first API call).
- Errors sent from
onCaughtError/onUncaughtErrorand the API client to your error-monitoring service, with the component stack.
Angular for comparison
Side note
| React | Angular |
|---|---|
| React Testing Library | Angular Testing Library (same queries) on top of TestBed |
| MSW | HttpTestingController (provideHttpClientTesting()), or MSW too |
Feature folders + index.ts | Feature folders with standalone components, a library's public-api.ts |
Route loader | a route resolve with a ResolveFn |
throw redirect('/login') | a functional CanActivateFn guard returning a UrlTree |
lazy: () => import(...) | loadComponent / loadChildren |
| Error boundary | a global ErrorHandler; no per-subtree boundaries |
<Suspense> + lazy() | @defer blocks with @placeholder and @loading |
The exercises
- getByRole, queryByRole and friends: role queries over an accessibility tree, with RTL's error rules.
- Match a route path:
:params,*splats, query strings and decoding. - waitFor and findBy: polling an assertion until it passes, without leaking timers.
- A mock API server (MSW-style): handlers, overrides,
once, fall-through and network errors with realRequest/Response. - Feature folder boundaries: enforce public APIs and layers on an import graph, and find feature cycles.
- A data router (nested routes and loaders): ranking, parallel loaders, redirects and error bubbling.
- Error and Suspense boundaries: a renderer where each boundary catches its own kind, with component stacks and a promise cache.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app