Testing React Applications with Jest and React Testing Library
Write maintainable tests with RTL—queries, user behavior, and mocking. Unit and integration testing in React.
Good tests catch regressions and document behavior. Here’s how to test React components with Jest and React Testing Library.
Testing React with Jest and RTL
Principles
Test behavior, not implementation — Query by role, label, or text the user sees. Avoid testing state or internal props.
React Testing Library — Renders components, provides screen and userEvent, and encourages accessible queries (getByRole, getByLabelText).
Jest — Runner and assertion library. Use for unit tests, component tests, and (with setup) integration tests. Mock modules with jest.mock() when necessary.
What to test — Critical paths: forms, navigation, conditional rendering. Skip testing every prop combination; focus on user flows.
Testing adoption (frontend teams):
Testing approach in React projects
Patterns
Render with render(<MyComponent />). Find elements with screen.getByRole('button', { name: 'Submit' }). Fire events with userEvent.click(). Assert with expect(...).toBeInTheDocument() or toHaveTextContent. Mock fetch with jest.spyOn(global, 'fetch') or MSW.
A practical RTL intro:
Takeaway
Use RTL’s queries and user-centric assertions. Write a few tests per feature; add more where risk is high. Keep tests fast and stable so the team actually runs them.