CodeBlanks Logo Icon CodeBlanks

Summary - RTL tests

Test a counter component by pressing the increment button.

Summary - RTL tests

In this group you learned RTL's core tools: render to mount, screen to query, getByRole priority, and userEvent for realistic events.

Remember: tests are written from a user's perspective. Accessible queries first, testId last resort. Use await for async operations.

Now combine what you learned in a small test: render, role query, click, assert.

Practice Toggle test

The Toggle component switches between "On" and "Off" text when the button is pressed. Write a test: set up a user with userEvent.setup(), render <Toggle />, find the button via screen.getByRole('button'), call await user.click(btn), and assert with expect(screen.getByText(/On/)).toBeInTheDocument(). The test must be async.

Starter code

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

// testi buraya yaz

Sample solution

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

test("toggle turns on", async () => {
  const user = userEvent.setup();
  render(<Toggle />);
  const btn = screen.getByRole("button");
  await user.click(btn);
  expect(screen.getByText(/On/)).toBeInTheDocument();
});

Questions and answers

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

1 What is the accessible query order?

  • getByRole first, getByTestId last Correct answer
  • getByText first, getByRole last
  • querySelector first, screen last
  • getByTestId first, getByRole last

Explanation: getByRole uses the accessibility tree, so it comes first.

2 Which keyword for an async test?

Question
test("async", ____ () => {
  await user.click(btn);
});
Answer
test("async", async () => {
  await user.click(btn);
});

Explanation: async callback allows await.

All lessons in Intermediate