Lesson 13 of 14 · 18m
Testing Components Like a User
Testing Library's one rule, getByRole doubling as an a11y check, msw at the network boundary, and what never earns a test.
The test suite that asserts on useState count, component internals, or a snapshot of a 200-node tree is not a safety net — it's a second implementation of your UI that breaks every refactor. Kent C. Dodds built Testing Library on one sentence: the more your tests resemble the way your software is used, the more confidence they can give you. Everything good in React testing follows from that; everything flaky follows from violating it.
Query like a user, assert like a user
render(<LoginForm />);
await user.type(screen.getByLabelText(/email/i), "a@b.co");
await user.click(screen.getByRole("button", { name: /sign in/i }));
expect(screen.getByText(/check your email/i)).toBeInTheDocument();getByRole with an accessible name is doing two jobs at once — it finds the element the way a screen reader would and it fails when your a11y is broken. A getByTestId("submit-btn") finds the node and learns nothing; a missing getByRole("button") is a real accessibility bug the test caught for free. userEvent over fireEvent for the same reason: user.type produces the actual keydown/input/change sequence a human causes; fireEvent can fabricate sequences no user generates.
What earns a test, and what never does
- Earns: user-visible state transitions — the form goes
idle → submitting → error, the error is announced, retry works. Error paths, boundary states, the four fetch states. Anything a user would file a bug about. - Never: that
useStatewas called, that a specific child rendered, that a mock of an internal function was invoked. Refactor the component, keep identical behavior, and these tests fail anyway — teaching the suite that green means "nothing changed internally," which is exactly backwards. - Never: giant snapshots.
expect(container).toMatchSnapshot()on a whole page rots — the diff becomes noise and the test gets--u-updated into meaninglessness without anyone reading it.
// what a real RTL test looks like end-to-end
it("shows the server error and keeps the draft", async () => {
server.use(http.post("/api/comment", () => new HttpResponse(null, { status: 500 })));
render(<CommentForm />);
await user.type(screen.getByLabelText(/comment/i), "ship it");
await user.click(screen.getByRole("button", { name: /post/i }));
expect(await screen.findByRole("alert")).toHaveTextContent(/try again/i);
expect(screen.getByLabelText(/comment/i)).toHaveValue("ship it");
});Three things are being asserted there that an implementation test would miss: the error surfaces as an alert role (announced by screen readers — the a11y contract is the test), the request actually reached the endpoint msw mocked, and the user's input survived the failure. Refactor the component's internals completely — swap useState for useReducer, split it into children — and the test still passes, because the user-facing behavior didn't change. That is the property you're paying for.
The boundary you mock is the network
Testing Library plus Vitest/Jest covers component logic; mock service worker (msw) intercepts fetch at the network so tests assert "given a 500 response, the error state renders" — not "the internal fetch mock was called." For the flows where the DOM isn't enough — real navigation, real browser APIs — Playwright drives an actual browser and finds the bugs jsdom's approximation never will. The split in practice: Vitest + Testing Library + msw for component behavior, Playwright for a handful of critical end-to-end paths (signup, checkout) — not a pyramid, a chosen set.
Field notes
getByRolecoverage doubles as an a11y smoke test — a component you can't query by role is usually a component with a semantic problem.- StrictMode's double-render will expose a test that relied on effects running once; write assertions about final state, not about how many times anything ran.
- A test that can't describe the user action it's simulating in one sentence is testing the wrong layer.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Building a Modern App With React, Vite, and Tailwind CSS: The Complete 2025 Guide
React for the UI, Vite for the build tooling, Tailwind for the styles. This is the stack most new frontend projects start with in 2025. This guide wires all three together from scratch and builds a real application structure you can actually start a production project from.
What is Vite? The Build Tool That Made Frontend Development Fast Again
Vite replaced Webpack for a lot of teams without much fanfare. Native ES modules, a dev server that starts in milliseconds, and a production build that doesn't require understanding 300 lines of config. Here's how it works and why the switch is worth it.
What is React? The JavaScript Library That Changed Frontend Development
React is a JavaScript library for building user interfaces. Facebook built it in 2013, open-sourced it, and the entire frontend ecosystem reorganized itself around it. Here is how the component model works, why it took over, and what you need to know before writing a single line.
Angular 18: Deferred Views & Built-in Control Flow
The newest release of Angular – which is Angular 18 – is planned to be released on May 22nd, 2024. This is Google's super popular TypeScript based webapp framework that allows developers to create amazing web applications. The features, changes, and goodies of this release are deferrable views…