Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Tooling and Patterns

Testing Web Components

Learn what to test in a custom element, how to render it in a fixture, wait for updates, simulate events and test shadow DOM, with a tiny runnable test harness.

A component is a small program with an input side (attributes, properties, slots, user events) and an output side (rendered DOM, events, form values, accessibility state). Testing it means driving the inputs and checking the outputs, in a real browser DOM. That is what separates web component tests from plain function tests: you need a DOM, custom element registration and often real layout.

Test runners such as Web Test Runner, Vitest browser mode, Playwright and Cypress need a package manager and Node, so they are shown read-only here. The runnable examples use a hand-written 20-line harness (a labelled stand-in) so you can see the shape of a test without tooling.

What to test

Aim at behavior that people or other code depend on, not at internals.

  1. Public API: attributes and properties produce the right output; defaults are sensible.
  2. Events: the right CustomEvent fires with the right detail after the right action.
  3. Slots and structure: slotted content ends up in the right place.
  4. Forms: FormData contains the value; reset and validation behave.
  5. Accessibility: role, name, state, keyboard operation and focus.
  6. Lifecycle: listeners are cleaned up on disconnect; reconnecting works.

Avoid asserting on private class names or exact internal markup; those make tests brittle when you refactor.

The test shape: arrange, act, assert

flowchart LR
  A["Arrange<br/>create element, attach to DOM"] --> B["Act<br/>set property, click, dispatch event"]
  B --> C["Wait<br/>for the update to finish"]
  C --> D["Assert<br/>check DOM, events, state"]

Most component tests follow these four steps.

The wait step matters. Components that batch updates (like the library-style examples in the previous lesson) do not update the DOM synchronously. A test must await the element's update promise, or a microtask or animation frame, before asserting.

A tiny harness and a first test

Testing a counter with a 20-line harness

Three tests pass and the deliberately wrong one fails with a readable message. That is the loop in miniature: create a fixture (a fresh element), act through the public API or real DOM events, assert on the result.

Real tools (read-only)

A real test file with Web Test Runner and @open-wc/testing:

JavaScript
import { fixture, html, expect, oneEvent } from "@open-wc/testing";
import "./x-counter.js";

it("announces count changes", async () => {
  const el = await fixture(html`<x-counter></x-counter>`);
  setTimeout(() => el.shadowRoot.querySelector("button").click());
  const event = await oneEvent(el, "count-change");
  expect(event.detail.count).to.equal(1);
});

it("passes the accessibility audit", async () => {
  const el = await fixture(html`<x-counter></x-counter>`);
  await expect(el).to.be.accessible();
});

Useful pieces: fixture renders and waits for the first update; oneEvent returns a promise for the next event; .to.be.accessible() runs the axe engine. With Playwright you would locate through shadow DOM using its built-in piercing selectors, which suits end-to-end tests.

Testing shadow DOM

  • Open roots are easy: el.shadowRoot.querySelector(...).
  • Closed roots hide the tree; test them through the public API and visible behavior only.
  • Prefer user-facing queries (roles, labels, text) over class names where your tooling supports them.
  • Simulate real input where possible: click(), dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })).

Timing and async

If your element updates in a microtask, wait for it:

JavaScript
el.count = 5;
await Promise.resolve();   // or await el.updateComplete in Lit
expect(textOf(el)).toBe("5");

Never use arbitrary setTimeout(..., 500) sleeps: they make suites slow and flaky. Wait for a specific event, promise or condition.

Visual and cross-browser testing

Unit tests do not catch layout bugs. Add visual regression screenshots for key states (default, hover, focus, disabled, dark theme) and run the suite in Chromium, Firefox and WebKit, since component APIs such as ElementInternals and :state() have differing support. Check browser support tables when adopting a newer API.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should most component tests assert on?

    Behavior-based tests survive refactoring; internal markup assertions break easily.
  2. 2. Why wait before asserting after changing a property?

    Batched renders happen in a microtask or frame, so assert after the update has completed.
  3. 3. How do you query inside an open shadow root in a test?

    An open shadowRoot is available as a property, so you can query inside it.
  4. 4. What is a fixture?

    A fixture creates and attaches the element under test, giving every test a clean starting point.

Summary

  • Test public behavior: API, events, slots, forms, accessibility and lifecycle.
  • Follow arrange, act, wait, assert, and wait for specific signals, not sleeps.
  • Open shadow roots are reachable in tests; closed ones are tested via behavior.
  • Real runners (Web Test Runner, Playwright, Cypress) are read-only here; the harness is a stand-in.
  • Add accessibility, visual and cross-browser checks for confidence.

Next: Lazy Loading and Distributing Components