React Testing Library Basics

React Testing Library essentials for component testing.

Basic Rendering

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

Render component
render(<MyComponent />);

With props
render(<MyComponent name="John" />);

Get container
const { container } = render(<MyComponent />);

Queries

By role
screen.getByRole("button", { name: /submit/i });

By label text
screen.getByLabelText("Username");

By placeholder
screen.getByPlaceholderText("Enter email");

By text
screen.getByText("Hello World");

By test ID
screen.getByTestId("custom-element");

Query Variants

getBy - throws if not found
screen.getByText("text");

queryBy - returns null if not found
screen.queryByText("text");

findBy - async, waits for element
await screen.findByText("text");

getAllBy - multiple elements
screen.getAllByRole("listitem");

User Interactions

Click
const button = screen.getByRole("button");
await userEvent.click(button);

Type
const input = screen.getByRole("textbox");
await userEvent.type(input, "Hello");

Clear
await userEvent.clear(input);

Select
const select = screen.getByRole("combobox");
await userEvent.selectOptions(select, "option1");