React ยท Chapter 35 of 42

Testing Basics

Testing React components ensures your UI behaves correctly as your codebase grows. The most common tools are Vitest or Jest (test runners) combined with React Testing Library (for rendering and querying components).

React Testing Library encourages testing components the way users interact with them โ€” via visible text and roles, not internal implementation details.

Rendering and querying

`render(<Component />)` mounts a component in a virtual DOM; `screen.getByText()` or `getByRole()` find elements to assert against.

Simulating interaction

`fireEvent.click()` or `userEvent.click()` simulate user interactions like clicks and typing to test behavior.

Example 1 (jsx)
import { render, screen, fireEvent } from "@testing-library/react";

test("increments counter on click", () => {
  render(<Counter />);
  fireEvent.click(screen.getByText("Count: 0"));
  expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
Output
โœ“ increments counter on click

The test renders Counter, simulates a click, and asserts the new text.

Key points

  • Vitest/Jest run tests; React Testing Library renders and queries components.
  • Test components by simulating real user behavior, not internal state.
  • getByRole/getByText find elements the way users perceive them.
  • fireEvent/userEvent simulate clicks, typing, and other interactions.
๐Ÿ’ก Note: Avoid testing implementation details like internal state โ€” test observable behavior instead.

๐Ÿ“ Quick Quiz

1. What library is commonly used to render/query components in tests?

2. What testing philosophy does RTL encourage?

3. What function simulates a user click in tests?