Skip to main content
← Guides

Guide

happy-dom vs jsdom (2026): Which Is Faster for Vitest?

Updated PkgPulse Team6 min read
0

happy-dom runs 2-4x faster than jsdom in Vitest. See real benchmarks, DOM API compatibility gaps, and a migration checklist for switching test environments.

Contents

TL;DR

Choose happy-dom when your component suite passes its compatibility checks and a local timing comparison shows a useful gain. Keep jsdom where its implementation fits the APIs your tests use. Vitest defaults to node, so install and select either DOM emulator explicitly. Neither provides browser layout or rendering. Use a real browser for those assertions.

Key Takeaways

  • Vitest defaults to node — select happy-dom or jsdom for DOM tests.
  • Install the selected emulator as a development dependency.
  • happy-dom can be faster, but Vitest's docs do not establish a universal speed ratio.
  • Jest defaults to node from version 27 — select jsdom explicitly.
  • Neither emulator renders a page — test layout and paint in a real browser.

What These Libraries Do

Both jsdom and happy-dom implement the browser DOM and Web APIs in Node.js, allowing component tests to run without a real browser:

Test runner (Node.js)
  ↓
DOM simulation (jsdom OR happy-dom)
  ↓
Your React/Vue component
  ↓
Rendered virtual DOM
  ↓
Assertions via Testing Library

Neither is a real browser — they are JavaScript approximations of browser APIs. For true cross-browser testing or tests that depend on real CSS rendering, layout, and paint behavior, use Playwright or Cypress against a real browser. jsdom and happy-dom exist to make component unit tests fast and runnable in Node.


Performance Benchmark

Vitest describes happy-dom as faster than jsdom with fewer implemented APIs. That is a qualitative comparison, not a prediction for a React component suite. The former timing tables had no pinned versions or reproducible fixture and have been removed.

Measure your own suite before migrating. Keep Node, Vitest, framework, emulator versions, worker count and machine limits fixed. Record cold startup separately from repeated execution, run both environments several times, and compare test failures alongside elapsed time. A faster run that skips an assertion is not a successful migration.


Configuration

Install the emulator before configuring Vitest. Install both if you use per-file fallbacks:

npm install --save-dev happy-dom jsdom @testing-library/jest-dom

Select the default for your project, or override it per file:

// vitest.config.ts — global environment setting
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    environment: 'happy-dom', // Switch here: 'happy-dom' | 'jsdom' | 'node'
    setupFiles: ['./src/test/setup.ts'],
  },
});
// src/test/setup.ts — works with both environments
import '@testing-library/jest-dom/vitest';
// Adds toBeInTheDocument, toHaveValue, toBeVisible, etc.

For per-file overrides, add a comment at the very top of the test file:

// src/components/chart.test.tsx
// @vitest-environment jsdom
// This file relies on an API behavior verified in jsdom

import { render, screen } from '@testing-library/react';
import { ChartComponent } from './ChartComponent';

test('renders chart with correct labels', () => {
  render(<ChartComponent data={[1, 2, 3]} />);
  expect(screen.getByRole('img', { name: /chart/i })).toBeInTheDocument();
});

For Jest, install jest-environment-jsdom to select jsdom, or the maintained happy-dom adapter:

npm install --save-dev @happy-dom/jest-environment
// jest.config.cjs
module.exports = {
  testEnvironment: '@happy-dom/jest-environment',
};

Jest changed its default to node in version 27. Vitest includes environment adapters, but you must install the emulator package.


API Compatibility Gaps

Treat API compatibility as a property of the installed versions and your test, rather than assuming every browser API is present.

CSS and layout — jsdom explicitly does not implement layout. Computed style support is not evidence that either emulator computes element geometry, flex layout or paint like a browser. Keep those checks in browser tests.

Navigation — jsdom supports parts of the history API, but assigning window.location.href does not navigate to a new document. Use a browser when navigation itself is the assertion.

Observers — check whether the installed emulator provides ResizeObserver or IntersectionObserver. jsdom does not provide them as standard built-ins. A mock can exercise the component's response to an event, but it does not test browser intersection or layout calculations.

Shadow DOM — both projects implement Web Components features. Test the custom elements and event behavior you use instead of assuming an overall winner.

Canvas — jsdom documents an optional native canvas backend. Without a backend, do not expect a working 2D drawing context. A mock or happy-dom implementation is not proof of rendering fidelity. Use a browser for pixel assertions.

These constraints follow the jsdom documentation and happy-dom project documentation.


Migration Checklist

Install happy-dom, then change the environment and investigate every failure. Migration effort depends on the APIs your suite exercises.

Step 1: Install happy-dom and update vitest.config.ts

// Before
environment: 'jsdom'

// After
environment: 'happy-dom'

Step 2: Run your test suite

pnpm vitest run

Step 3: Triage failures

Most failures fall into two categories:

  • Real failures you hadn't caught — bugs in your components that jsdom was silently ignoring. Fix these normally.
  • happy-dom API gaps — tests that fail because happy-dom doesn't support a specific API your test uses.

For the second category, the fix is usually a per-file environment override:

// Add to the top of the affected test file
// @vitest-environment jsdom

Step 4: Add targeted mocks for common APIs

Some mocks are needed in both environments but are often added during migration:

// src/test/setup.ts — common browser API mocks
import '@testing-library/jest-dom/vitest';

// Deterministic matchMedia mock for tests that need controlled results
Object.defineProperty(window, 'matchMedia', {
  writable: true,
  value: vi.fn().mockImplementation((query: string) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: vi.fn(),
    removeListener: vi.fn(),
    addEventListener: vi.fn(),
    removeEventListener: vi.fn(),
    dispatchEvent: vi.fn(),
  })),
});

// scrollTo — stubbed in both environments
window.scrollTo = vi.fn();

Step 5: Accept the hybrid approach

Vitest supports per-file environment overrides. Keep a jsdom fallback where it reproduces the behavior you need. Measure the resulting suite instead of assuming a particular split of files or percentage speedup.


Package Health

PackageRoleUpstream
jsdomDOM emulatorjsdom project
happy-domDOM emulator, maintained by David Ortner and contributorshappy-dom project
jest-environment-jsdomJest adapter for jsdomJest configuration
@happy-dom/jest-environmentJest adapter for happy-domhappy-dom setup

Use the package pages for live activity signals. Downloads include automated installs and transitive dependencies and do not measure active users.


When to Choose

Choose happy-dom when:

  • You're using Vitest and want to evaluate a faster DOM emulator
  • Your measured suite improves after switching environments
  • Your tests are standard React, Vue, or Svelte component tests using Testing Library
  • You want faster CI feedback loops without sacrificing meaningful coverage
  • You're willing to add per-file jsdom fallbacks for the small percentage of edge-case tests

Choose jsdom when:

  • You're using Jest and have explicitly configured jsdom
  • Your tests depend on complex CSS cascade, computed styles, or CSS custom properties
  • Your tests pass with jsdom's implementation of the APIs you use
  • You want maximum browser API compatibility and don't want to manage per-file environment overrides
  • Your team is unfamiliar with happy-dom and migration risk outweighs the speed benefit

Testing Library Compatibility and Practical Gotchas

Testing Library's queries use DOM APIs, but that does not guarantee identical behavior in every emulator. Exercise accessible names, focus, events and any third-party component behavior before switching. If a component reads computed styles, distinguish a returned CSS value from a layout result.

For components driven by observers, a controlled mock can isolate the component response. Trigger the callback with representative entries in the test. This does not validate browser geometry.

class MockResizeObserver {
  observe() {}
  unobserve() {}
  disconnect() {}
}
globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;

When the Speed Difference Actually Matters

Measure environment initialization and test execution separately. Suites with many small files can spend more time creating environments, while suites dominated by application work may see little change. Use the same worker count and test selection in each run.

Keep the migration only if the saved time justifies its compatibility and maintenance cost. Vitest's environment guide supports a qualitative speed tradeoff, not the former 2–4× ratio or a predicted CI reduction.

Source notes