Sub topic 3
Rendering components and using screen
This chapter assumes you know React function components, props, and state. It also assumes you have a Jest or Vitest project with jsdom and jest-dom set up, as covered in the previous chapter. Here you will learn what render does and why queries go through screen.
What render does
render mounts your component into a detached div that it appends to document.body. The environment is jsdom, so no real browser is involved. The component runs its normal lifecycle: state initializes, effects fire, and the DOM updates as it would in an app.
Testing Library cleans up automatically after each test when your runner exposes afterEach globally. Jest does this by default. Vitest does so only if you set globals: true. Without globals, call cleanup yourself.
// vitest.setup.js, only needed when globals are off
import { afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
afterEach(cleanup);Using screen
render returns an object with bound queries, but the usual style is to query through screen. It is an object that holds every query, bound to document.body. Because it needs no destructuring, you do not have to change the render line when you add a new query.
// Counter.jsx
import { useState } from 'react';
export function Counter({ initial = 0 }) {
const [count, setCount] = useState(initial);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
</div>
);
}
// Counter.test.jsx
import { render, screen } from '@testing-library/react';
import { Counter } from './Counter';
test('renders the initial count from props', () => {
render(<Counter initial={5} />);
expect(screen.getByText('Count: 5')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Increment' })).toBeInTheDocument();
});The test passes props as a user of the component would. It then looks only at what appears on the page.
What else render returns
The result object has a few members you will use now and then:
| Member | Purpose |
|---|---|
| `container` | The `div` that holds your component. Useful for rare cases with no accessible query. |
| `rerender` | Renders the same tree again with new props. |
| `unmount` | Removes the component so you can test cleanup logic. |
| `baseElement` | The element queries are bound to, `document.body` by default. |
rerender is the one worth knowing. It tests how a mounted component reacts to changed props, without losing its state.
// Greeting.jsx
export function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
// Greeting.test.jsx
import { render, screen } from '@testing-library/react';
import { Greeting } from './Greeting';
test('updates 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();
});Common mistakes
- Reaching into
container. Calls such ascontainer.querySelector('.count')tie the test to class names. Preferscreenqueries. - Calling
rendertwice in one test. Both trees land in the samedocument.body, so queries may match elements from both. Usererenderto change props. - Rendering outside a test. Rendering at module level skips the per-test cleanup and leaks state between tests.
Exercise
A test renders <Greeting name="Ada" />, then calls render(<Greeting name="Grace" />) to check the new name, and screen.getByRole('heading') throws an error. Why does it fail, and what should the test call instead?
Show answer
The second render adds a second tree to document.body, so two headings exist and getByRole throws because it finds multiple matches. Use rerender(<Greeting name="Grace" />) from the first render result, which updates the existing tree.