render and screen
- React course
- Intermediate
- Lesson 70/80
- 4 min
Learn to render a component and query it with screen.
render and the screen
The render call mounts a component into a virtual DOM and returns an object. Its container property holds the root node; unmount removes the component.
In most tests you query via screen without touching container. Sometimes container.querySelector is needed for a CSS selector.
RTL auto-cleans after each test; adding afterEach is optional.
Query priority
RTL recommends queries in accessibility order: getByRole first, then getByLabelText, getByPlaceholderText, getByText, and finally getByTestId.
This order keeps tests close to real user experience. Screen reader users see roles and labels; so should tests.
Use getByTestId only when no alternative exists; users cannot see test ids.
Practice SaveButton test
Write a test that renders SaveButton, finds it with screen.getByRole('button', { name: /save/i }), and asserts with expect(btn).toBeInTheDocument(). Wrap it in test().
Starter code
import { render, screen } from "@testing-library/react";
import { SaveButton } from "./SaveButton";
// testi buraya yazSample solution
import { render, screen } from "@testing-library/react";
import { SaveButton } from "./SaveButton";
test("save button is visible", () => {
render(<SaveButton />);
const btn = screen.getByRole("button", { name: /save/i });
expect(btn).toBeInTheDocument();
});Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which finds a button by role?
- screen.getByRole('button') Correct answer
- screen.findByClass('btn')
- screen.getById('button')
- screen.getByTag('button')
Explanation: Screen.getByRole('button'). Accessible queries come first.
2 Find button by role
render(<SaveButton />);
const btn = screen.____(
/kaydet/i
);
render(<SaveButton />);
const btn = screen.getByRole(
/kaydet/i
);
Explanation: getByRole is the accessible query.
3 Match query priority
| Term | Meaning |
|---|---|
getByRole |
1st priority |
getByLabelText |
2nd priority |
getByText |
Middle |
getByTestId |
Last resort |