React › Testing

What is React Testing Library and how does its approach to testing differ from testing internal implementation details?

Beginner

Answer

React Testing Library encourages testing a component the way an actual user would interact with it, such as finding a button by its visible text and clicking it, rather than checking internal details like a component's specific state values. This makes tests more reliable, since they keep passing even if the internal code changes, as long as the actual user experience stays the same.
import { render, screen, fireEvent } from '@testing-library/react';

test('button increments count when clicked', () => {
  render(<Counter />);
  const button = screen.getByText('Count: 0');
  fireEvent.click(button);
  expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
Real-world example A team's test for a counter button keeps passing even after they rewrite the component from using useState to useReducer internally, since the test only ever checked what the user actually sees and clicks on the screen.

Common follow-ups: Why is testing implementation details, like internal state, considered a less reliable approach?;What is the difference between getByText and queryByText when an element might not exist?