Skip to content

DOM Testing

In one line

DOM testing verifies code that manipulates the web page structure, using a simulated DOM (jsdom) in Node.js or a real browser.

In simple words

DOM testing is for code that interacts with the web page — creating elements, changing text, handling events, etc. Since this code needs a DOM to work, you need a DOM environment for testing.

Two approaches:

  1. jsdom: A pure JavaScript DOM simulation that runs in Node.js. Fast, no browser needed, but doesn't support layout/rendering or all browser APIs.
  2. Real browser: Use Playwright or Cypress to test in an actual browser. Slower but fully realistic.

For unit and component testing, jsdom is usually sufficient and much faster. Jest uses jsdom by default for browser-environment tests. For E2E testing, you need a real browser.

DOM testing libraries like Testing Library help you query elements and simulate user interactions in the simulated DOM.

Example

javascript
// dom.test.js — Testing DOM with Testing Library
import { render, screen, fireEvent } from '@testing-library/dom';
import { createButton } from './button';

test('button increments count on click', () => {
  const container = document.createElement('div');
  createButton(container);  // renders <button>Count: 0</button>

  const btn = screen.getByText(/Count:/);
  fireEvent.click(btn);
  fireEvent.click(btn);

  expect(btn.textContent).toBe('Count: 2');
});

// Tests interact with real DOM nodes (created in jsdom)
// and assert on what the user actually sees.

DOM testing renders components into a real (jsdom) DOM, then interacts via fireEvent and asserts on visible text — testing what the user sees, not internal component state.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary