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.
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.
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
What is jsdom and what can't it do?
What goes in a Vitest setup file for React Testing Library and why?
What is the difference between vitest and vitest run?
Why does RTL 16 make you install @testing-library/dom yourself?
Preview
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