React Testing Library
In one line
React Testing Library tests components like a user would — querying by role and text, not by implementation details.
In simple words
React Testing Library (RTL) is the standard way to test React components. Its guiding principle is: 'test components the way users interact with them.'
Instead of testing internal component state or methods (implementation details), RTL encourages you to:
- Render the component
- Find elements by their accessible role, text content, or label — the same way users and screen readers find them
- Interact using
userEvent(clicks, typing) — simulating real user behavior - Assert on what's visible to the user (text, presence of elements)
This approach has big benefits:
- Tests don't break when you refactor internals (because you test behavior, not implementation)
- Tests verify accessibility (if you can query by role, the component is accessible)
- Tests reflect real user experience
RTL's philosophy: 'The more your tests resemble the way your software is used, the more confidence they can give you.'
Example
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
test('button click increments counter', async () => {
render(<Counter />);
expect(screen.getByText('Count: 0')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'Increment' }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});The test finds the button by its accessible role and name, clicks it, and checks the visible text.
Related terms
Related Resources
Related Lessons
- React Testing
Testing React components.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.