HomeReact
Chapter 23

23 — Testing React Applications

Testing with Vitest (test runner) + React Testing Library (RTL) — the modern standard. Tests should resemble how users interact with your app.

Testing Pyramid

LevelToolSpeedWhat It Tests
UnitVitestFastPure functions, hooks, utilities
ComponentRTL + VitestMediumRendering, user interactions
IntegrationRTL + MSWMediumMultiple components + API mocking
E2EPlaywright/CypressSlowFull app in real browser

React Testing Library Philosophy

> "The more your tests resemble the way your software is used, the more confidence they can give you."

  • Query by role, label, text — not by CSS class or test ID
  • Fire real user events with userEvent (not fireEvent)
  • Assert what the user sees, not implementation details

Query Priority (Best → Last Resort)

PriorityQueryExample
1stgetByRolegetByRole("button", { name: "Submit" })
2ndgetByLabelTextgetByLabelText("Email")
3rdgetByPlaceholderTextgetByPlaceholderText("Search...")
4thgetByTextgetByText("Welcome")
5thgetByDisplayValuegetByDisplayValue("current value")
LastgetByTestIdgetByTestId("custom-element")

File

  • testing.tsx — unit tests, component tests, user interaction, async testing, mocking, hook testing, MSW setup