Sub topic 14
Choosing a Test Environment: node, jsdom, or happy-dom
This chapter assumes you have read the previous chapter on vitest.config.js and can write tests with describe, it, expect, vi.fn, and lifecycle hooks. It also assumes you know basic DOM APIs such as document.createElement, addEventListener, and querySelector.
A test environment is the set of global objects that Vitest provides while your test file runs. Your code may need document and window, or it may only need Node.js modules such as fs. The environment controls which of these exist. If you choose the wrong one, tests fail with ReferenceError: document is not defined. They can also pass while checking behavior a real browser would never show.
The Three Common Environments
Vitest runs every test file inside Node.js. The environment only changes which globals are installed on top of Node before the file is loaded.
| Environment | What it provides | Extra package | Typical use |
|---|---|---|---|
| `node` (default) | Node globals only: `process`, `Buffer`, `fetch`, `setTimeout` | none | Pure logic, servers, CLI tools, data transforms |
| `jsdom` | A simulated browser: `window`, `document`, `localStorage`, `Event`, `HTMLElement` | `jsdom` | DOM code and UI components where standards coverage matters |
| `happy-dom` | A lighter simulated browser with the same kinds of globals | `happy-dom` | DOM code where start-up and run speed matter more |
Vitest also includes an edge-runtime environment for code aimed at edge platforms. This chapter covers the three you will meet most often.
How it works internally
Before Vitest loads a test file, it reads the environment setting for that file. If the setting is jsdom or happy-dom, Vitest creates a new simulated window and copies its properties, such as document, navigator, and HTMLElement, onto the global scope. Then it imports your test file. When the file finishes, Vitest tears that window down.
Two consequences follow from this:
- Every test file gets its own fresh DOM. Changes made in one file never leak into another file.
- All tests inside one file share the same DOM. Elements appended by the first test are still there when the second test runs, unless you remove them.
Setting the Environment
For the whole project
Install the DOM library you want, then name it in the config:
npm install -D jsdom// vitest.config.js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'jsdom',
},
})If you skip the install step, Vitest stops with an error telling you the package is missing. It does not quietly fall back to node.
For a single file
Most projects are mostly logic with a few DOM modules. The default node environment is the fastest, so you can keep it as the project setting and switch individual files with a docblock comment. The comment must sit at the very top of the file, before any imports:
// @vitest-environment jsdom
import { describe, it, expect, afterEach } from 'vitest'
function renderGreeting(container, name) {
const p = document.createElement('p')
p.className = 'greeting'
p.textContent = `Hello, ${name}`
container.appendChild(p)
return p
}
describe('renderGreeting', () => {
afterEach(() => {
document.body.innerHTML = ''
})
it('appends a greeting paragraph', () => {
renderGreeting(document.body, 'Ada')
const p = document.querySelector('.greeting')
expect(p.textContent).toBe('Hello, Ada')
})
it('starts each test with an empty body', () => {
expect(document.querySelectorAll('.greeting')).toHaveLength(0)
})
})The afterEach hook does real work here. Without it, the second test would find the paragraph left over from the first test and fail. Whether it fails would then depend on test order, which is exactly the kind of flakiness you want to avoid.
The block-comment form /** @vitest-environment happy-dom */ also works.
Mixing environments by folder
If your client and server code live in separate folders, you can define projects. Each project has its own include pattern and environment:
// vitest.config.js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
projects: [
{
test: {
name: 'server',
include: ['src/server/**/*.test.js'],
environment: 'node',
},
},
{
test: {
name: 'client',
include: ['src/client/**/*.test.js'],
environment: 'jsdom',
},
},
],
},
})Testing Events in a Simulated DOM
Simulated DOMs dispatch events through the real listener machinery. That lets you test interaction logic without a browser:
// @vitest-environment happy-dom
import { it, expect, vi, afterEach } from 'vitest'
function setupCounter(button, onChange) {
let count = 0
button.addEventListener('click', () => {
count += 1
button.textContent = `Clicked ${count}`
onChange(count)
})
}
afterEach(() => {
document.body.innerHTML = ''
})
it('updates the label and reports each click', () => {
const button = document.createElement('button')
document.body.appendChild(button)
const onChange = vi.fn()
setupCounter(button, onChange)
button.click()
button.dispatchEvent(new MouseEvent('click', { bubbles: true }))
expect(button.textContent).toBe('Clicked 2')
expect(onChange).toHaveBeenLastCalledWith(2)
})The same test passes under jsdom. Changing only the docblock line is a quick way to compare the two libraries on your own code.
jsdom vs happy-dom: Decision Criteria
Both libraries implement DOM standards in JavaScript, and neither is a browser. They differ in what they prioritize.
| Concern | jsdom | happy-dom |
|---|---|---|
| Maturity and spec coverage | Older and broader. Edge cases tend to match the standards. | Newer. Covers common APIs, but rarer APIs may be missing or behave differently. |
| Speed | Slower to start and heavier per file | Usually faster, which shows up in suites with many DOM files |
| Ecosystem expectations | The long-standing default in many tutorials and libraries | Widely used. Occasionally a third-party library assumes jsdom behavior. |
| Configuration | `environmentOptions.jsdom` (for example `url`) | `environmentOptions.happyDOM` (for example `url`, `width`, `height`) |
A practical rule: start with jsdom for correctness. Switch to happy-dom if DOM test runtime becomes a real cost, then run the suite. If something breaks, investigate whether the gap is in happy-dom or in your code.
Gotchas and Failure Modes
No layout engine
Neither library computes layout. getBoundingClientRect() returns zeros, offsetWidth is 0, and CSS from stylesheets does not affect geometry. A test that asserts on element size or position will either fail or pass for the wrong reason. Test that kind of code in a real browser.
// @vitest-environment jsdom
import { it, expect } from 'vitest'
it('has no real layout', () => {
const div = document.createElement('div')
div.style.width = '200px'
document.body.appendChild(div)
expect(div.style.width).toBe('200px')
expect(div.getBoundingClientRect().width).toBe(0)
})The inline style is stored as a string, but nothing turns it into geometry.
Missing browser APIs
Some APIs are not implemented, such as window.matchMedia in jsdom and IntersectionObserver. Code that calls them throws TypeError: ... is not a function or a ReferenceError. Use vi.stubGlobal to provide a stub, and restore it afterwards:
// @vitest-environment jsdom
import { it, expect, vi, afterEach } from 'vitest'
function prefersDark() {
return window.matchMedia('(prefers-color-scheme: dark)').matches
}
afterEach(() => {
vi.unstubAllGlobals()
})
it('reads the colour scheme preference', () => {
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })))
expect(prefersDark()).toBe(true)
})State that outlives a test
Within a file, localStorage, document.cookie, document.body, and event listeners on window all persist between tests. Clear them in afterEach, for example with localStorage.clear() and document.body.innerHTML = ''. Otherwise test order decides the outcome.
DOM globals in node-only code
If shared utility code checks typeof window !== 'undefined' to detect a browser, running its tests under jsdom sends it down the browser branch. Test such code in both environments, using two files or two projects, so each branch actually runs.
Paying for an environment you do not need
Setting environment: 'jsdom' globally makes every file, including pure logic tests, pay for creating a window. In a large suite this adds measurable time. Keep node as the default and opt in per file or per project.
Exercise
A file contains two tests. The first appends a <li> to document.body. The second asserts that document.querySelectorAll('li') has length 0. The second test fails under jsdom, but when you run it alone with .only it passes. Explain why and give the fix.
Show answer
All tests in one file share a single simulated DOM, so the <li> added by the first test is still there when the second test runs. Run alone, the second test starts with an empty body. Add afterEach(() => { document.body.innerHTML = '' }) so every test starts from a clean DOM.
Exercise
Your project's config sets environment: 'node'. One file, widget.test.js, needs document. Write the line you add, say where it goes, and say what else you must install.
Show answer
Add // @vitest-environment jsdom as the very first line of widget.test.js, before any imports. Install the library with npm install -D jsdom, or use happy-dom in the comment and install happy-dom instead.
Exercise
A test checks that a tooltip is positioned 8 pixels below its trigger by comparing getBoundingClientRect().top values. It passes in jsdom even after you break the positioning code. Why, and what should you do?
Show answer
jsdom has no layout engine, so getBoundingClientRect() returns zeros for every element and the comparison never reflects real positions. Either test only the logic that computes the offset, for example a pure function that returns 8, or move the positioning test to a real browser using Vitest browser mode or an end-to-end tool.