Component Testing with Testing Library
Test components the way users use them: query by role and label, simulate real interactions and mock the network with MSW.
Intermediate · about 5 hours · difficulty 3/5
Learn first: Testing Fundamentals with Vitest, Forms in React with React Hook Form
Testing Library (@testing-library/react and friends for Vue, Svelte and Angular) renders components in a simulated DOM (jsdom or happy-dom) and encourages tests that resemble how people use your app. If your test finds a button by its accessible name, it also checks that screen reader users can find it.
Query priority
getByRole("button", { name: /add to cart/i })for almost everything.getByLabelTextfor form fields,getByTextfor non-interactive content.getByTestIdonly as a last resort.
Variants: getBy throws if missing, queryBy returns null (for asserting absence), findBy waits for async content.
Interactions
Use @testing-library/user-event (await user.click(button), await user.type(input, "hello")), which simulates real keyboard and pointer sequences more faithfully than firing single events. Assert with @testing-library/jest-dom matchers like toBeInTheDocument, toBeDisabled and toHaveValue.
Async and network
Mock HTTP at the network level with MSW so components use their real fetch and query code. Wrap components in the providers they need (router, QueryClient, theme) with a custom render helper.
Other tools
- Browser mode in Vitest or Playwright component tests run in a real browser when jsdom is not enough.
- Storybook interaction and visual tests pair well with component stories.
- Snapshot tests are easy to write and easy to rubber-stamp; use them sparingly.
Good enough to move on
You can test a form that validates, submits to a mocked API and shows success and error states, using only role and label queries and user-event.
Key concepts
- render and screen
- Queries by role and label
- getBy, queryBy and findBy
- user-event interactions
- jest-dom matchers
- Mocking the network with MSW
- Custom render with providers
- Vitest browser mode
Mini project
Write component tests for your signup form and product list: validation errors, successful submission against an MSW handler, a server error state and filtering, all without test ids.
Check yourself
When should you use findByRole instead of getByRole?
Free resources
- Testing Library (Testing Library)
- Which query should I use? (Testing Library)
- Mock Service Worker (MSW)