Skip to main content
← Guides

Guide

happy-dom vs jsdom vs linkedom 2026

Updated PkgPulse Team9 min read
0

Compare happy-dom, jsdom, and linkedom for DOM simulation in JavaScript testing 2026. Speed benchmarks, compatibility, Vitest defaults, and when to use each.

Contents

TL;DR

Use happy-dom or jsdom for Node-based component tests, and linkedom when server-side HTML parsing and serialization are the main job. Vitest defaults to node, and Jest has defaulted to node since version 27. Install and select the DOM emulator explicitly. Benchmark your own suite before choosing on speed, and use a real browser for layout or rendering assertions.

Key Takeaways

  • happy-dom can be faster than jsdom, but the official Vitest guide gives no universal multiplier.
  • jsdom implements browser standards with documented limitations, including no layout engine.
  • linkedom targets server-side DOM work rather than full browser emulation.
  • Vitest 2 Browser Mode is opt-in with --browser or browser.enabled: true.
  • @happy-dom/jest-environment is the maintained Jest adapter.
  • Testing Library compatibility needs a test against the component and emulator versions you install.

Why DOM Simulation Matters for Test Speed

When you run npm test on a React component, Node.js doesn't have a browser DOM. Libraries like happy-dom, jsdom, and linkedom provide a JavaScript implementation of browser APIs so tests can run in Node.js without launching Chrome.

Environment startup and DOM operations can affect suite time. Measure both using the same test files, dependency versions and worker count. The former 500-component timings lacked a reproducible fixture and have been removed.

Neither emulator is a complete browser. Use a real browser to test CSS layout, paint and browser-specific interaction behavior.


jsdom: The Battle-Tested Standard

npm: jsdom | role: explicitly selected DOM environment for Vitest or Jest

jsdom implements browser standards in Node.js. Jest used jsdom by default before version 27; current Jest projects must select it explicitly and install the environment package.

npm install --save-dev jest-environment-jsdom
# or if using Vitest:
npm install --save-dev jsdom

Vitest configuration with jsdom:

// vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    environment: 'jsdom',
    globals: true, // makes describe, it, expect available globally
    setupFiles: ['./src/test-setup.ts'],
  },
})

Jest configuration (select jsdom explicitly):

// jest.config.js
module.exports = {
  testEnvironment: 'jsdom',
  setupFilesAfterEnv: ['@testing-library/jest-dom'],
}

What jsdom covers well:

import { render, screen, fireEvent } from '@testing-library/react'
import { Button } from './Button'

test('button handles click events', () => {
  const handleClick = vi.fn()
  render(<Button onClick={handleClick}>Click me</Button>)

  const button = screen.getByRole('button', { name: 'Click me' })
  fireEvent.click(button)

  expect(handleClick).toHaveBeenCalledTimes(1)
})

test('form submission with jsdom', () => {
  const onSubmit = vi.fn(e => e.preventDefault())
  render(
    <form onSubmit={onSubmit}>
      <input type="text" placeholder="Name" />
      <button type="submit">Submit</button>
    </form>
  )

  const input = screen.getByPlaceholderText('Name')
  fireEvent.change(input, { target: { value: 'John' } })
  fireEvent.click(screen.getByRole('button'))

  expect(onSubmit).toHaveBeenCalledTimes(1)
})

jsdom's scope:

  • DOM queries, events, MutationObserver and parts of the history API.
  • No CSS layout engine or WebGL renderer.
  • Assigning window.location.href does not navigate to a new document.
  • Canvas drawing requires the optional backend documented for the installed jsdom release.
  • Resource loading is configurable; do not assume all network requests are mocked automatically.

See the jsdom README for its supported options and limits. The component examples above assume a Vitest project with globals enabled and application components supplied.


happy-dom: Speed-First Implementation

npm: happy-dom | role: explicitly selected DOM environment for Vitest

happy-dom implements browser APIs without a graphical interface. Vitest describes it as faster than jsdom with some APIs missing. That does not establish a coverage percentage for component tests.

npm install --save-dev happy-dom

Vitest configuration with happy-dom:

// vitest.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    environment: 'happy-dom', // Explicit choice; Vitest defaults to node
    globals: true,
  },
})

File-level environment override (when you need jsdom for specific tests):

// ComplexComponent.test.tsx
// @vitest-environment jsdom  ← overrides global happy-dom for this file

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

This lets you use happy-dom globally (for speed) and fall back to jsdom for tests that need deeper compatibility.

Speed comparison: the former 100-component timing table had no pinned versions, test fixture or run output. It does not establish a 5–10× suite speedup. Compare the installed emulators on your own suite before migrating.

The snippets below illustrate application tests. Supply the component imports, Testing Library setup and userEvent import in a configured project. They are not benchmark fixtures.

Where happy-dom shines:

// Application test excerpt — verify behavior in the selected environment
test('counter increments', async () => {
  render(<Counter initialCount={0} />)

  const button = screen.getByRole('button', { name: '+' })
  await userEvent.click(button)
  await userEvent.click(button)

  expect(screen.getByText('2')).toBeInTheDocument()
})

test('form validation shows errors', async () => {
  render(<LoginForm />)

  await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))

  expect(screen.getByText('Email is required')).toBeInTheDocument()
  expect(screen.getByText('Password is required')).toBeInTheDocument()
})

test('dropdown opens on click', async () => {
  render(<Select options={['React', 'Vue', 'Svelte']} />)

  await userEvent.click(screen.getByRole('combobox'))

  expect(screen.getByRole('listbox')).toBeInTheDocument()
  expect(screen.getAllByRole('option')).toHaveLength(3)
})

Where happy-dom has gaps:

// ❌ CSS computed styles (almost never correct in any DOM simulator)
const el = document.querySelector('.my-element')
window.getComputedStyle(el).display // unreliable in happy-dom AND jsdom

// ❌ ResizeObserver (may need polyfill)
// ❌ Some canvas operations
// ❌ Complex navigation scenarios (use jsdom or Playwright)
// ❌ CSS custom properties affecting layout

React Testing Library compatibility: happy-dom supports Testing Library workflows, but exercise the interactions your components use before changing environments.


linkedom: Server-Side Rendering Focused

npm: linkedom | use case: SSR/HTML parsing

linkedom takes a different approach: it's built around a linked list DOM structure (hence the name) that makes serialization (innerHTML, outerHTML) extremely fast. It's the right tool for server-side HTML generation, not for testing interactive components.

npm install linkedom
import { parseHTML } from 'linkedom'

// Fast for parsing and serialization
const { document, window } = parseHTML(`
  <!doctype html>
  <html>
    <head><title>Test</title></head>
    <body>
      <div id="app">
        <h1>Hello World</h1>
        <ul>
          <li>Item 1</li>
          <li>Item 2</li>
        </ul>
      </div>
    </body>
  </html>
`)

// Traverse and query
const items = document.querySelectorAll('li')
console.log(items.length) // 2

// Modify and serialize
const app = document.getElementById('app')
app.appendChild(document.createElement('p')).textContent = 'Added!'
console.log(document.body.innerHTML) // Serializes fast

Where linkedom is used:

  • Server-side HTML rewriting where the runtime and package build are compatible
  • SSR frameworks that need fast HTML parsing on the edge
  • Web scraping in serverless environments where Puppeteer is too heavy
  • Testing HTML templates without full browser simulation needs

Why linkedom isn't ideal for component testing:

linkedom provides DOM and event APIs, but its project explicitly targets server-side rendering rather than full browser simulation. Do not treat it as a drop-in Vitest environment or assume browser focus and interaction semantics. Test its parsing and serialization behavior against your inputs.


Comparison Table

Needjsdomhappy-domlinkedom
Vitest DOM environmentSelect jsdomSelect happy-domCustom integration required
Jest DOM environmentInstall jest-environment-jsdomInstall @happy-dom/jest-environmentCustom integration required
Browser layout and paintUse a real browserUse a real browserUse a real browser
Component interactionsVerify required API behaviorVerify required API behaviorNot a browser-emulation substitute
Server HTML parsingSupportedSupportedPrimary use case
Suite speedMeasure locallyMeasure locallyNot the same testing workload

If you are choosing a component-test environment, see the focused happy-dom and jsdom comparison alongside this broader table.


Migration: jsdom → happy-dom in Vitest

Install happy-dom as a development dependency, then change the configuration. Keep jsdom installed for any per-file fallbacks:

// Before (vitest.config.ts)
export default defineConfig({
  test: { environment: 'jsdom' }
})

// After
export default defineConfig({
  test: { environment: 'happy-dom' }
})

Run the suite and investigate behavioral differences. Passing tests alone do not validate browser layout or rendering. If some fail, check:

  1. ResizeObserver: If a test needs controlled observer behavior, use a mock. This no-op example does not simulate resize events:

    // test-setup.ts
    global.ResizeObserver = class ResizeObserver {
      observe() {}
      unobserve() {}
      disconnect() {}
    }
    
  2. CSS media queries: Mock window.matchMedia when tests need deterministic query results:

    Object.defineProperty(window, 'matchMedia', {
      writable: true,
      value: (query: string) => ({
        matches: false,
        media: query,
        onchange: null,
        addListener: vi.fn(),
        removeListener: vi.fn(),
        addEventListener: vi.fn(),
        removeEventListener: vi.fn(),
        dispatchEvent: vi.fn(),
      }),
    })
    
  3. Specific failing tests: Use the @vitest-environment jsdom comment to opt specific test files back to jsdom without changing the global config.


When to Use Each

Use jsdom if:

  • Your Jest project explicitly uses jsdom and its behavior fits your tests
  • Test reliability is more important than speed
  • You have complex DOM interaction tests with keyboard navigation, focus management, or media queries
  • You're testing forms with complex browser-specific behavior

Use happy-dom if:

  • Your Vitest suite passes compatibility checks with happy-dom
  • Test speed is a priority (CI time, developer feedback loops)
  • Your tests are primarily render-and-query patterns
  • You can maintain the mocks and fallbacks your suite needs

Use linkedom if:

  • You're parsing HTML on the server or edge (not testing)
  • You need fast HTML rewriting in Cloudflare Workers
  • You're building an SSR renderer that needs fast DOM serialization
  • You're doing web scraping in a Node.js environment without Puppeteer

Use Playwright component testing if:

  • You need real browser APIs (canvas, WebGL, actual CSS layout)
  • You're testing visual appearance (screenshots)
  • Integration-level testing that should match real browser behavior exactly

Methodology

Official sources support the environment defaults and API scope, not a universal speed ranking. No component-suite benchmark is claimed here. The former unversioned timings, download counts and package-size estimates have been removed.

Source notes


Choosing the Right Environment for Your Test Suite

One practical consideration teams overlook when switching DOM simulators is the interaction with TypeScript's lib compiler option. Both happy-dom and jsdom inject globals (window, document, navigator) into the Node.js test process, but the TypeScript type definitions come from @types/jsdom for jsdom and from happy-dom's own bundled types. If your tsconfig.json includes "lib": ["DOM"], you are already pulling in browser type definitions — the question is just whether the runtime implementation matches those types at test time. Happy-dom tracks the TypeScript DOM types closely, but occasional gaps appear in newer browser APIs before happy-dom has implemented them. When a test fails with a "not implemented" error rather than an assertion error, that is a happy-dom coverage gap — the fix is either a polyfill in your setup file or a per-file environment override to jsdom. Tracking these gaps with a comment linking to the happy-dom GitHub issue is a good practice for teams maintaining a large test suite across both environments.

Looking for testing package data? Check PkgPulse's comparison of jsdom and happy-dom for live health scores, download trends, and maintenance analysis.

Compare happy-dom and jsdom package health on PkgPulse.

Related: Best JavaScript Testing Frameworks Compared (2026), JavaScript unit-test runner comparison, The Consolidation of JavaScript Testing: How Vitest Won.