Testing React Components

Testing is a critical part of the software development lifecycle. It ensures that your components work as expected and helps prevent regressions when you make changes.

The Testing Stack

Writing a Basic Test

RTL encourages you to test your components as a user would interact with them.

JavaScript

import { render, screen } from '@testing-library/react';
import HelloWorld from './HelloWorld';

test('renders hello world message', () => {
  render(<HelloWorld />);
  const linkElement = screen.getByText(/hello world/i);
  expect(linkElement).toBeInTheDocument();
});

Common RTL Queries

Simulating User Interaction

You can use the fireEvent or userEvent libraries to simulate clicks, typing, and other actions.

JavaScript

import { render, screen, fireEvent } from '@testing-library/react';

test('increments counter on click', () => {
  render(<Counter />);
  const button = screen.getByRole('button');
  fireEvent.click(button);
  expect(screen.getByText(/clicked 1 times/i)).toBeInTheDocument();
});

Note: Good tests should be resilient. Avoid testing internal state or private methods; instead, focus on what the user sees and interacts with.