tech

Testing React Components

reacttestingfrontend

Testing Library encourages testing components the way users interact with them.

The Philosophy

Test behavior, not implementation. Do not test internal state or private methods. Test what the user sees and does.

Example

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

test('submits form', async () => {
  render(<LoginForm />);
  await userEvent.type(screen.getByLabelText('Email'), '[email protected]');
  await userEvent.click(screen.getByText('Submit'));
  expect(await screen.findByText('Welcome')).toBeInTheDocument();
});

If your test breaks after refactoring internals without changing behavior, it tests the wrong thing.