| | |

Vitest 16 🧪 Test Environment — node, jsdom, and happy-dom selection

⏱️ Estimated read: 8 min | |

Vitest runs tests in Node.js, but the environment option decides what global objects the test code sees. The default is node, which is the bare Node.js runtime with no DOM. The jsdom environment provides a browser-like DOM by loading the jsdom package, and happy-dom provides a faster, lighter DOM by loading the happy-dom package . The choice is not cosmetic: a component test that calls document.createElement fails in node, and a test suite that constructs a full jsdom for every file pays a cost that happy-dom avoids.

This chapter covers the three environments, the environmentOptions configuration that tunes each one, and the per-file control comment that overrides the global setting. The sections that follow walk through the node default, the jsdom and happy-dom trade-off, and the mixed configuration that runs one suite with two environments.

Key point: The environment option selects the global runtime for the test file; node is the default, jsdom is the accurate browser emulation, and happy-dom is the faster one with a narrower API surface, and the @vitest-environment comment overrides the setting for a single file.


a. The node default and the browser-like alternatives

The node environment is the default. It runs the test code in the Node.js runtime with the Node globals (process, Buffer, fs) and no window, document, or navigator. It is the correct choice for a test that exercises a pure function, an API client, or a server-side module that does not touch the DOM.

// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    environment: "node", // the default
  },
});

The jsdom environment loads the jsdom package and populates the global namespace with a browser-like window, document, navigator, and the related APIs . It is the most complete emulation, and it is the correct choice for a test that depends on a browser API that happy-dom does not implement—matchMedia with specific behavior, MutationObserver edge cases, or a library that assumes a full jsdom .

The happy-dom environment loads the happy-dom package, which provides a subset of the browser APIs at a lower construction cost . It is the correct choice for the majority of component tests: React, Vue, and Svelte components that use the common DOM APIs, the Testing Library queries, and the basic DOM manipulation. A project’s migration from jsdom to happy-dom measured a 61% reduction in environment setup time and a 28% reduction in wall-clock time, with the same 9,112 tests passing .


b. The trade-off and the failure modes

The speed advantage of happy-dom comes with a narrower API surface, and the gap produces test failures that are not bugs in the application. The documented examples are the matchMedia implementation, the Location object’s accessor properties, and the CSS color serialization.

jsdom does not ship a matchMedia, and a project that stubs it with a default { matches: false } gets a desktop viewport by accident. happy-dom ships a real matchMedia over a 1024-wide window, and the same test that passed under the stub fails because the real implementation reports a narrow viewport and the layout folds the actions into an overflow menu . The fix is environmentOptions.happyDOM: { width: 1280 }, which states the viewport explicitly.

The Location object is the second case. A test that copies the location with { ...globalThis.location, assign: vi.fn() } works under jsdom because the members happen to be on the instance, and fails under happy-dom because the members are accessors on the prototype and the spread copies nothing . The fix is a helper that carries the members by name, not a change to the environment.

The CSS color serialization is the third case. jsdom normalizes red to rgb(255, 0, 0) in a computed style, and happy-dom does not. A test that asserts on the normalized value fails, and the fix is to assert on the value the environment actually produces, or to keep that one test file on jsdom .

The failures are not a reason to avoid happy-dom. They are a reason to run the suite under happy-dom first, fix the environment-specific assumptions, and keep jsdom for the files that genuinely need the fuller implementation.


c. The environmentOptions and the per-file override

The environmentOptions option passes configuration to the environment’s setup. The jsdom and happyDOM keys hold the options for each, and the options are scoped to their environment, which lets a project configure both in the same config .

export default defineConfig({
  test: {
    environment: "happy-dom",
    environmentOptions: {
      happyDOM: {
        width: 1280,
        height: 720,
        url: "http://localhost:3000",
      },
    },
  },
});

The per-file override is the @vitest-environment comment at the top of the file. The comment sets the environment for the file’s tests, and the global environment option applies to every file that does not have one .

// @vitest-environment jsdom
import { test, expect } from "vitest";

test("uses the full jsdom", () => {
  expect(typeof window).not.toBe("undefined");
});

The comment is the mechanism for the mixed configuration. A suite runs under happy-dom by default, and the one file that needs jsdom carries the comment and the dependency stays installed for that file . The alternative is the projects configuration, which runs a group of files under one environment and another group under a different one, but the comment is the lighter-weight form for a single file.


Complete Example Session

// ============================================
// PART 1: THE GLOBAL ENVIRONMENT
// ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    environment: "happy-dom",
    environmentOptions: {
      happyDOM: { width: 1280, height: 720 },
    },
  },
});

// ============================================
// PART 2: THE NODE TEST
// ============================================
// src/api.test.ts
import { test, expect } from "vitest";
import { parsePort } from "./api";

test("parses a port", () => {
  expect(parsePort("8080")).toBe(8080);
});
// Runs in happy-dom, but the test does not touch the DOM.

// ============================================
// PART 3: THE PER-FILE OVERRIDE
// ============================================
// src/legacy-dom.test.ts
// @vitest-environment jsdom
import { test, expect } from "vitest";

test("uses the full jsdom", () => {
  expect(typeof window).not.toBe("undefined");
});

// ============================================
// PART 4: THE ENVIRONMENT-SPECIFIC FAILURE
// ============================================
// A test that relies on jsdom's CSS color normalization
// fails under happy-dom. The fix is to assert on the value
// the environment produces, or to keep that file on jsdom.

The parts covered the global environment, a test that does not need the DOM, the per-file override, and the environment-specific failure.


Quick Reference

Environments

EnvironmentProvidesUse For
nodeNode.js globalsPure functions, server modules
jsdomFull browser emulationComplex DOM, libraries needing full API
happy-domLighter browser emulationComponent tests, fast suites
edge-runtimeVercel edge runtimeEdge functions

Configuration

OptionPurpose
environmentGlobal environment
environmentOptions.jsdomjsdom setup options
environmentOptions.happyDOMhappy-dom setup options
// @vitest-environment namePer-file override

Trade-offs

Aspectjsdomhappy-dom
SpeedSlowerFaster
API coverageBroaderNarrower
matchMediaStub neededReal implementation
CSS colorNormalizedNot normalized

Best Practices

✅ Do This:

// Use happy-dom for the component suite
environment: "happy-dom"                                       // ✅

// Set the viewport explicitly
environmentOptions: { happyDOM: { width: 1280 } }              // ✅

// Override per file when the full jsdom is needed
// @vitest-environment jsdom                                    // ✅

❌ Don’t Do This:

// Use node for a component test
environment: "node" // no document                             // ❌

// Assume happy-dom has every jsdom API
// (it does not)                                               // ❌

// Rely on jsdom's CSS normalization in a happy-dom suite
// (the assertion will fail)                                   // ❌

Common Pitfalls

PitfallWhy It HappensFix
document is undefinednode environmentUse happy-dom or jsdom
matchMedia behaves differentlyReal implementation vs stubSet environmentOptions.happyDOM.width
CSS assertion failsjsdom normalizes, happy-dom does notAssert on the produced value
Slow suitejsdom construction per fileSwitch to happy-dom

Real-World Examples

1. node environment

environment: "node"

2. happy-dom environment

environment: "happy-dom"

3. jsdom environment

environment: "jsdom"

4. happy-dom width

environmentOptions: { happyDOM: { width: 1280 } }

5. jsdom URL

environmentOptions: { jsdom: { url: "http://localhost:3000" } }

6. Per-file override

// @vitest-environment jsdom

7. edge-runtime

environment: "edge-runtime"

8. Check the environment

expect(typeof window).toBe("undefined"); // node

9. CSS assertion

// happy-dom: not normalized; assert on the raw value

10. Mixed suite

happy-dom default + @vitest-environment jsdom for one file

Visual

The Environment Selection

┌─────────────────────────────────────────────────────────┐
│  environment: "node"                                    │
│    → Node globals, no DOM                               │
│                                                         │
│  environment: "happy-dom"                               │
│    → Browser-like, faster                               │
│                                                         │
│  environment: "jsdom"                                   │
│    → Browser-like, fuller API                           │
└─────────────────────────────────────────────────────────┘

The Trade-off

┌─────────────────────────────────────────────────────────┐
│  SPEED                          ACCURACY                │
│  happy-dom  ◄──────────────────►  jsdom                 │
│                                                         │
│  Faster, narrower API           Slower, fuller API      │
│  Component tests                Complex DOM             │
└─────────────────────────────────────────────────────────┘

The Per-File Override

┌─────────────────────────────────────────────────────────┐
│  // @vitest-environment jsdom                           │
│  import { test, expect } from "vitest";                 │
│                                                         │
│  This file runs in jsdom; every other file uses         │
│  the global `environment` option.                       │
└─────────────────────────────────────────────────────────┘

The Viewport Stub

┌─────────────────────────────────────────────────────────┐
│  jsdom: no matchMedia → stub with matches: false        │
│  happy-dom: real matchMedia over 1024 → narrow layout   │
│                                                         │
│  Fix: environmentOptions.happyDOM.width = 1280          │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Default environmentnode
Full browser emulationjsdom
Faster browser emulationhappy-dom
Environment optionsenvironmentOptions
Per-file override// @vitest-environment name
Edge runtimeedge-runtime

Key takeaways:

  • The environment option selects the global runtime. node is the default and has no DOM; jsdom and happy-dom provide a browser-like DOM, and edge-runtime emulates Vercel’s edge runtime .
  • happy-dom is faster, jsdom is more complete. The speed advantage of happy-dom comes from a narrower API surface, and the gap produces test failures that are environment assumptions rather than application bugs .
  • environmentOptions tunes the environment. The happyDOM and jsdom keys hold the setup options, and the options are scoped to their environment, which lets a project configure both .
  • The per-file comment overrides the global setting. // @vitest-environment jsdom at the top of a file runs that file in jsdom while the rest of the suite uses the global environment .
  • The migration is a fix-the-assumptions exercise. The matchMedia stub, the Location spread, and the CSS normalization are the three common failures, and each has a specific fix that keeps the suite on happy-dom .

Remember: The environment is the runtime the test code sees, and the choice is a trade-off between speed and API completeness. Use happy-dom for the component suite and jsdom for the files that need the fuller implementation. Set the viewport explicitly, keep the jsdom dependency for the files that carry the comment, and fix the environment-specific assumptions rather than bending the tests around them.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!