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

  1. Install @testing-library/react, @testing-library/jest-dom, and jest.
  2. Import render and screen from the testing library.
  3. Query elements with getByRole, getByLabelText, or getByText.
  4. Use userEvent or fireEvent to simulate interactions.
  5. 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.