CodeBlanks Logo Icon CodeBlanks

React Testing Library

Learn the basics of writing component tests with RTL.

React Testing Library

React Testing Library (RTL) is a library that tests components the way a user does. You query DOM nodes and make assertions about them; you test the real user experience, not internal implementation.

RTL's core philosophy is test your application the way users use it. That is why it favours accessible queries (getByRole, getByText) over data-testid.

This approach keeps tests stable across refactors: tests look at the user interface, not at internal wiring.

render and screen

render mounts the component into a virtual DOM and returns query helpers. screen provides global queries bound to the document; in most tests you use methods like screen.getByText.

Modern RTL recommends screen because it keeps imports short and lets queries run against the document.

getBy throws if not found; queryBy returns null; findBy awaits async results.

Practice First RTL test

Write a test that renders the Greeting component with the name="World" prop, finds the text "Hello World" via screen.getByText, and asserts it with expect(...).toBeInTheDocument(). Wrap it in test() or it().

Starter code

App.jsx
import { render, screen } from "@testing-library/react";
import { Greeting } from "./Greeting";

// testi buraya yaz

Sample solution

App.jsx
import { render, screen } from "@testing-library/react";
import { Greeting } from "./Greeting";

test("greeting shows text", () => {
  render(<Greeting name="World" />);
  expect(screen.getByText("Hello World")).toBeInTheDocument();
});

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is RTL's core philosophy?

  • Verify internal state
  • Test like a user Correct answer
  • Mock hooks
  • Call class components

Explanation: RTL aims to test as close to the user experience as possible.

2 Find text with screen

Question
import { render, screen } from "@testing-library/react";

render(<Button>Sil</Button>);

const btn = screen.____("Sil");
Answer
import { render, screen } from "@testing-library/react";

render(<Button>Sil</Button>);

const btn = screen.getByText("Sil");

Explanation: screen.getByText finds by text.

3 Match query types

Term Meaning
render Mounts to DOM
screen Global query
getByText Finds by text
findByText Awaits async

All lessons in Intermediate