How to write basic tests for React components with React Testing Library
· Category: React
Short answer
React Testing Library helps you test components from the user's perspective by rendering them into a virtual DOM and querying elements by accessible attributes.
Steps
- Install
@testing-library/react,@testing-library/jest-dom, andjest. - Import
renderandscreenfrom the testing library. - Query elements with
getByRole,getByLabelText, orgetByText. - Use
userEventorfireEventto simulate interactions. - Assert with Jest matchers and
expect(...).toBeInTheDocument().
Example
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Counter from './Counter';
it('increments when clicked', async () => {
render(<Counter />);
const button = screen.getByRole('button', { name: /increment/i });
await userEvent.click(button);
expect(screen.getByText('1')).toBeInTheDocument();
});
Tips
- Prefer queries that reflect how users find elements (
getByRole,getByLabelText). - Avoid testing implementation details like state or internal methods.
- Use
findBy*for async assertions when waiting for elements to appear.