Component Testing with React Testing Library

Test React components the way users use them: find elements by role and label, interact, and assert on what appears.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Testing Fundamentals with Vitest, Forms and User Input

React Testing Library encourages tests that resemble real usage. Instead of checking internal state, you find a button by its accessible name, click it and check what the user sees.

Core ideas

  • Render a component, then query with getByRole, getByLabelText and getByText. Role-based queries also nudge you toward accessible markup.
  • Simulate interaction with user-event (typing, clicking, tabbing).
  • Use findBy queries for things that appear asynchronously.
  • Mock network calls at the boundary with MSW (Mock Service Worker) instead of mocking fetch everywhere.

What to test

  • Forms: validation messages, disabled submit, success and error states.
  • Conditional UI: empty, loading and error states.
  • Interactive widgets: filters, tabs, modals.

Skip testing static markup and third-party library internals.

Server components

Async server components are harder to unit test; cover them with integration or end-to-end tests and keep their logic in plain functions you can unit test.

Pitfalls

  • Querying by CSS class or test ids for everything.
  • Snapshot tests of large trees that everyone updates without reading.
  • Forgetting to await async UI, causing flaky tests.

You are ready to move on when your application form has tests for validation errors, a successful submit and a server error, using role-based queries and MSW.

Key concepts

  • render and screen queries
  • Role and label queries
  • user-event interactions
  • Async UI with findBy
  • Mocking APIs with MSW
  • Testing custom hooks

Mini project

Write component tests for your internship filters and application form: filter results update, validation messages appear, submit is disabled while pending and server errors are shown, with API calls mocked by MSW.

Check yourself

Why is getByRole('button', { name: 'Apply' }) usually a better query than a test id?

Free resources