CodePark/ questions / Jest & Vitest
START PRACTICINGPRACTICE
Frontend question · Testing › Jest & Vitest

In a Vitest project with globals: false, component tests start failing with 'Found multiple elements' because elements from earlier tests are still in the DOM. What is the most likely cause?

React Testing Library's automatic cleanup hooks into a global afterEach, which doesn't exist without globals, so you must call cleanup() in a setup file

RTL (React Testing Library) unmounts rendered trees after each test only if it finds a global afterEach to hook into. With Vitest globals off, that global does not exist, so old renders stay in the DOM. Fix it: add afterEach(() => cleanup()) in a setup file, or set globals: true. The option about tests running in parallel is wrong. Tests inside one file run one after another by default.