Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 17.2 — Setting Up Vitest and Testing Library
React · Example 2 of 2

Why the setup file cleans up after each test

render() appends a new container to document.body every time. Without cleanup the second test finds Asha's heading and Ravi's, so getByRole throws. cleanup() unmounts every tree render() created and removes the containers.

Vitest runs your test files in Node with jsdom pretending to be a browser, React Testing Library renders components into that fake page, and a setup file adds jest-dom matchers and cleans up after each test.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a vitest.config.js for a project that wants jsdom, no globals, and a setup file at test/setup.js. Then write that setup file.

02

Write a real test file (Vitest syntax, jest-dom) for a Badge component that renders <span>New</span> when isNew is true and nothing otherwise.

Explain it without notes

01

What is jsdom and what can't it do?

02

What goes in a Vitest setup file for React Testing Library and why?

03

What is the difference between vitest and vitest run?

04

Why does RTL 16 make you install @testing-library/dom yourself?

Why the setup file cleans up after each test

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

✓ greets Asha
✗ greets Ravi: Found multiple elements with the role "heading"
headings on the page: 2
after cleanup(): 0