Sub topic 3
Rendering Components and Using screen
This chapter covers the two functions you will use in almost every test: render, which mounts a component into a DOM, and screen, which queries what was mounted. It looks at what render does, what it returns, and when you should not use those return values.
This chapter assumes you have read the earlier chapters on testing philosophy and environment setup. You should have a working Jest or Vitest project with jsdom and @testing-library/jest-dom registered. You should also be comfortable with React function components, props, and useEffect.
What render does
render takes a React element and mounts it into a real DOM tree provided by jsdom. Each call does the following:
- It creates a
divelement, called the container. - It appends the container to
document.body. - It creates a React root on the container and renders your element inside
act, so effects and initial state updates finish beforerenderreturns. - It returns an object of helpers.
Nothing is mocked. Your component runs with the real React renderer, real hooks, and real DOM nodes. The only fake part is the browser itself, which jsdom approximates.
A first test with screen
screen is an object whose queries are already bound to document.body. You import it next to render:
// Greeting.jsx
export function Greeting({ name }) {
return (
<section>
<h1>Hello, {name}</h1>
<p>Welcome back.</p>
</section>
);
}
// Greeting.test.jsx
import { render, screen } from '@testing-library/react';
import { Greeting } from './Greeting';
test('greets the user by name', () => {
render(<Greeting name="Ada" />);
expect(screen.getByRole('heading', { name: 'Hello, Ada' })).toBeInTheDocument();
expect(screen.getByText('Welcome back.')).toBeInTheDocument();
});Notice that the test never holds a reference to the rendered output. It asks the page for what a user would see: a heading with a given name and a paragraph with given text. This matches the behavior-first approach from the first chapter.
Why screen is preferred over destructured queries
render also returns the same queries, bound to the rendered container. This works:
const { getByText } = render(<Greeting name="Ada" />);
expect(getByText('Welcome back.')).toBeInTheDocument();Most teams use screen instead, for these reasons:
- You do not have to edit the destructuring list each time a test needs another query.
- Every query reads the same way, and the test reads like a description of the page.
- It also finds content that React renders outside your container, such as portals used by modals and tooltips. Container-bound queries miss that content.
- Autocomplete in editors works from a single import.
What render returns
The return value has more than queries. This table lists the parts you will meet most often.
| Property | What it is | Typical use |
|---|---|---|
| `container` | The `div` that `render` created | Rarely. Mostly an escape hatch |
| `baseElement` | The element queries are bound to, `document.body` by default | Rarely |
| `rerender(ui)` | Renders new UI into the same root | Changing props mid-test |
| `unmount()` | Unmounts the tree | Verifying cleanup logic |
| `asFragment()` | A `DocumentFragment` copy of the current DOM | Snapshot tests |
| `debug()` | Prints the DOM to the console | Debugging |
rerender: changing props on the same tree
rerender renders a new element into the existing root. React sees the same component type at the same position, so it updates the existing instance and keeps its state, as it would in a real app.
import { render, screen } from '@testing-library/react';
import { Greeting } from './Greeting';
test('updates the heading when the name prop changes', () => {
const { rerender } = render(<Greeting name="Ada" />);
expect(screen.getByRole('heading', { name: 'Hello, Ada' })).toBeInTheDocument();
rerender(<Greeting name="Grace" />);
expect(screen.getByRole('heading', { name: 'Hello, Grace' })).toBeInTheDocument();
expect(screen.queryByText('Hello, Ada')).not.toBeInTheDocument();
});Calling render a second time would not do the same thing. It would create a second container and a second, independent tree, and both would sit in document.body. Your queries could then find duplicates.
unmount: testing cleanup
Use unmount when the component has teardown logic, such as removing an event listener:
// ResizeLogger.jsx
import { useEffect } from 'react';
export function ResizeLogger({ onResize }) {
useEffect(() => {
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, [onResize]);
return <p>Listening for resize</p>;
}
// ResizeLogger.test.jsx
import { render } from '@testing-library/react';
import { ResizeLogger } from './ResizeLogger';
test('stops listening after unmount', () => {
const onResize = jest.fn();
const { unmount } = render(<ResizeLogger onResize={onResize} />);
window.dispatchEvent(new Event('resize'));
expect(onResize).toHaveBeenCalledTimes(1);
unmount();
window.dispatchEvent(new Event('resize'));
expect(onResize).toHaveBeenCalledTimes(1);
});The second assertion proves the effect cleanup ran. In Vitest, use vi.fn() instead of jest.fn().
Automatic cleanup
After each test, React Testing Library unmounts every tree that render mounted and removes its container. Without this, content from one test would leak into the next, and queries would find elements from earlier tests.
The library registers this cleanup by calling afterEach if the runner exposes it as a global. Jest does, so you need to do nothing.
Vitest does not expose globals by default. If you have not set globals: true in the Vitest config, the automatic hook is not registered, and tests that render the same text will start failing with "multiple elements" errors. Register cleanup yourself in the setup file:
// vitest.setup.js
import { afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
import '@testing-library/jest-dom/vitest';
afterEach(() => {
cleanup();
});Scoping queries with within
screen searches the whole body. When the same text appears in several regions, narrow the search with within, which binds the same queries to one element:
import { render, screen, within } from '@testing-library/react';
function Lists() {
return (
<div>
<section aria-label="Cart">
<ul>
<li>Pen</li>
<li>Ink</li>
</ul>
</section>
<section aria-label="Wishlist">
<ul>
<li>Pen</li>
</ul>
</section>
</div>
);
}
test('finds items inside one region', () => {
render(<Lists />);
const cart = screen.getByRole('region', { name: 'Cart' });
expect(within(cart).getByText('Ink')).toBeInTheDocument();
expect(within(cart).getAllByRole('listitem')).toHaveLength(2);
expect(screen.getAllByText('Pen')).toHaveLength(2);
});within still queries by user-visible attributes. It only limits where the search starts. The region is found by its role and accessible name, so the test does not depend on the markup structure.
When to use container
container is a plain DOM element, so container.querySelector('.card') works. It is an escape hatch, and you should avoid it. A CSS class or tag name is an implementation detail. Users cannot see it, and a refactor can change it without changing behavior. Reserve container for cases where no accessible query can express what you need, such as checking that a third-party library produced an SVG node.
Common errors
- Forgetting that
renderis synchronous for the first render only.renderfinishes the initial mount and effects insideact. Updates that happen later, such as after a fetch resolves, need the async queries covered in a later chapter. - Calling
rendertwice in one test to "update" props. Usererender. A secondrendercreates a second tree. - Importing
screenbut still destructuring queries fromrender. Both work, but mixing them makes tests inconsistent. Pickscreen. - Expecting
screento see another document. It is bound todocument.bodyof the current jsdom window. Content inside an iframe needs its own handling. - Expecting the container to be the root of your component. The container wraps your component's output. Its first child is the root element of your component, and a component can return several roots with a fragment.
Summary of the working model
render mounts into a real DOM and returns helpers. screen is your default way to query it. Use rerender to change props on the same tree, unmount to test teardown, and within to narrow a search. Treat container as a last resort, and make sure cleanup runs after every test.
Exercise
A test renders <Greeting name="Ada" />, then calls render(<Greeting name="Grace" />) to check the updated heading. The final screen.getByRole('heading') call throws an error. Why does it fail, and how do you fix the test?
Show answer
The second render call creates a second container and a second independent tree in document.body. Two headings now exist, so getByRole('heading') finds multiple matches and throws. Fix it by keeping the rerender function returned from the first render call and calling rerender(<Greeting name="Grace" />). That updates the existing tree in place.
Exercise
Your Vitest suite has two tests that each render a component showing "Welcome back." The first passes. The second fails with "Found multiple elements with the text: Welcome back." Name the likely cause and one fix.
Show answer
Automatic cleanup did not run, because Vitest does not expose afterEach as a global unless globals: true is set. The first test's DOM stayed in document.body. Fix it by registering afterEach(() => cleanup()) in the setup file, using cleanup from @testing-library/react, or by enabling globals: true in the Vitest config.