CodePark/ questions / Testing
START PRACTICINGPRACTICE
Frontend question · React › Testing

What are the guiding principles of React Testing Library?

test('adds a todo', async () => {
  const user = userEvent.setup();
  render(<TodoApp />);
  await user.type(screen.getByRole('textbox', { name: /new todo/i }), 'Milk');
  await user.click(screen.getByRole('button', { name: /add/i }));
  expect(screen.getByRole('listitem')).toHaveTextContent('Milk');
});

React Testing Library tells you to test components the way users use them, not how they are built inside. The guiding idea: the more your tests look like real use, the more confidence they give.

In practice:

  • Render the component.
  • Find elements the way a user or assistive technology, like a screen reader, would.
  • Interact with them.
  • Assert on what appears on the screen.

Prefer getByRole with an accessible name. Then use getByLabelText, getByText and similar. Use getByTestId only as a last resort.

Simulate interactions with @testing-library/user-event. It copies real browser event sequences more closely than fireEvent. For example, typing fires keydown, input and keyup for each character.

Avoid asserting on internal state, props or hook calls. Tests written this way survive refactors. They also push you toward accessible markup.

  • Test behaviour, not implementation details.
  • Query like a user: start with getByRole and a name.
  • Use getByTestId only as a last resort.
  • Use user-event for realistic interactions.
  • These tests survive refactors and encourage accessibility.