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
| Level | Tool | Speed | What It Tests |
|---|---|---|---|
| Unit | Vitest | Fast | Pure functions, hooks, utilities |
| Component | RTL + Vitest | Medium | Rendering, user interactions |
| Integration | RTL + MSW | Medium | Multiple components + API mocking |
| E2E | Playwright/Cypress | Slow | Full 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(notfireEvent) - Assert what the user sees, not implementation details
Query Priority (Best → Last Resort)
| Priority | Query | Example |
|---|---|---|
| 1st | getByRole | getByRole("button", { name: "Submit" }) |
| 2nd | getByLabelText | getByLabelText("Email") |
| 3rd | getByPlaceholderText | getByPlaceholderText("Search...") |
| 4th | getByText | getByText("Welcome") |
| 5th | getByDisplayValue | getByDisplayValue("current value") |
| Last | getByTestId | getByTestId("custom-element") |
File
testing.tsx— unit tests, component tests, user interaction, async testing, mocking, hook testing, MSW setup