Setting Up the jsdom Environment
What you'll learn: How to configure jsdom so Vitest can simulate browser APIs needed for testing React components.
Why You Need jsdom
React components expect to run in a browser—they create DOM elements, listen to events, and call browser APIs like document.querySelector() or window.localStorage. But your tests run in Node.js, which has no DOM. That's where jsdom comes in: it's a JavaScript implementation of web standards that lets Node.js pretend to be a browser.
Think of jsdom as a stage prop. Real tests run in a real theater (the browser), but unit tests run on a rehearsal stage (Node.js) with lightweight props (jsdom) that look real enough for the actors (your components) to perform.
Configuring the Environment
After installing jsdom (already covered in your dependencies setup), you tell Vitest to use it by adding the environment option to your vitest.config.ts:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'jsdom',
// Optional: make browser globals available
globals: true,
}
})
Now when your tests run, document, window, and DOM methods exist. React Testing Library can render components, fire events, and query elements—all without opening an actual browser.
What This Enables
With jsdom configured, your test files can now:
- Render React components using
render()from React Testing Library - Access
document.getElementById()and similar browser APIs - Simulate user interactions like clicks and typing
- Test components that use hooks like
useEffectthat depend on the DOM
Key Takeaway: Configuring environment: 'jsdom' in Vitest gives your React tests access to simulated browser APIs, enabling component rendering and interaction testing without launching a real browser.