How to test React components with Testing Library
· Category: React
How to test React components with Testing Library
Philosophy
Testing Library encourages tests that resemble how users interact with your app. Query elements by accessible roles and text rather than CSS selectors or component internals. This makes tests resilient to refactoring.
Basic Test
import { render, screen, fireEvent } from "@testing-library/react";
import Counter from "./Counter";
test("increments count on click", () => {
render(<Counter />);
const button = screen.getByRole("button", { name: /increment/i });
fireEvent.click(button);
expect(button).toHaveTextContent("1");
});
Async Testing
Use findBy queries for elements that appear after asynchronous operations:
const item = await screen.findByText("Loaded data");
Mocking
Mock external modules and API calls to isolate components. If you are testing authentication flows, understanding authentication vs authorization helps you mock the right user states. For API layer tests, what is REST API clarifies expected request shapes.
Avoid testing implementation details like state variables or internal functions. Focus on outcomes users can see and interact with.