npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@excom/nucleus-test

v0.3.0

Published

Vitest setup, matchers and helpers for testing Nucleus Stack apps and elements on happy-dom

Readme

nucleus-test

Test Nucleus Stack apps and custom elements in Vitest with one setup line: a browser-like DOM, HTML-aware matchers and helpers for clicks, events and fetch.

Features

  • One-line setup Vitest on happy-dom, patched for browser parity by @excom/nucleus-dom
  • Semantic DOM diffs Compare markup, not whitespace / attribute order; snapshots as readable HTML
  • Listener leak checks Count event listeners per element and assert them in one line
  • Fixtures / mocks Mount HTML, click, await events, mock fetch responses
  • Complexity snapshots Snapshot the engine and DOM work a test costs; a changed count flags a regression
  • Quiet logs console.log(element) prints <div#id>, not thousands of lines

Installation

Usage

Install vitest 4 and happy-dom (the version @excom/nucleus-dom pins) next to this package, and add the setup file to your Vitest config.

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

export default defineConfig({
  test: { environment: "happy-dom", setupFiles: ["@excom/nucleus-test/setup"] },
});

A test file imports everything from one place, Vitest's own API and @open-wc/semantic-dom-diff included.

import { afterEach, click, expect, fixture, it, waitForEvent } from "@excom/nucleus-test";
import "./x-drawer";

afterEach(() => {
  document.body.innerHTML = "";
});

it("opens on click", async () => {
  const drawer = fixture(`<x-drawer><button>Cart</button></x-drawer>`);
  await waitForEvent(drawer, "x-drawer-open", () => click(drawer.querySelector("button")!));
  expect(drawer).equalTag(`<x-drawer open></x-drawer>`);
});

Matchers

expect(list).dom.to.equal(`<ul><li>Tea</li></ul>`); // semantic HTML diff
expect(drawer).equalTag(`<x-drawer open></x-drawer>`); // own tag + attributes, children ignored
expect(drawer).toMatchListeners({ click: 1, keydown: 1 }); // exact listener counts per type
expect(window).toContainListeners({ resize: 0 }); // listed types only: none left after removal
expect(list).toMatchInlineSnapshot(); // elements snapshot as indented HTML

getEventListeners(target) returns the recorded listeners by type; clearEventListeners(target) forgets them. Both are globals too.

Types for the matchers and globals come with any import from @excom/nucleus-test; the setup file declares none.

Helpers

  • fixture(html) mounts html in document.body and returns its first element
  • click(target, init?) dispatches a bubbling, cancelable, composed click; false when prevented
  • waitForEvent(target, type, trigger?, delay?) resolves delay ms after type fires, rejects after 1 s; trigger runs once it listens
  • wait(ms?) resolves after ms
  • readFileRelative(import.meta.url, relPath) reads relPath, relative to the test file, as text
  • readDemo(import.meta.url, name) reads support/demos/<name>.html from a test in support/tests
  • spyFetch(response, ms?) stubs fetch with a response (or a function returning one) after ms; status 200 and a JSON content-type by default; vi.restoreAllMocks() / restoreMocks: true restores fetch
  • serveStatic(root, { fallback?, api? }) is a fetch stand-in serving a directory at the page's origin, like a static dev server, with an SPA fallback and /api/* sent to a handler: vi.spyOn(globalThis, "fetch").mockImplementation(serveStatic(root, { fallback: "index.html" }))
const fetchSpy = spyFetch({ body: JSON.stringify({ items: 3 }) });
// … the element under test fetches
expect(fetchSpy).toHaveBeenCalledWith("/api/cart");

spyFetch(() => ({ status: 404 }), 300); // a 404 after 300 ms

Console output goes through consoleSinks: spy on one to capture / silence it, e.g. vi.spyOn(consoleSinks, "warn").mockImplementation(() => {}).

Complexity snapshots

Count the work a test causes, in units (rule passes, binding reads / writes, DOM queries and writes), never time, and snapshot it. A changed count is a regression signal: review it, then update deliberately with -u. Counts are exact only when the test drives the page itself; a suite that polls a live app on timers and simulated latency gets different counts each run, so measure a single element or a controlled scenario there.

trackComplexity(engine, { settle? }) snapshots every test in the file (or describe) as <test> > complexity 1. engine is the engine's own counters, Quark.meter for Quark; settle lets the page finish before the count is taken. Call it after hooks that clear the DOM, since after hooks run last-registered first.

import { afterEach, trackComplexity } from "@excom/nucleus-test";
import { Quark } from "@excom/quark";

afterEach(() => {
  document.body.innerHTML = "";
});
trackComplexity(Quark.meter, { settle: () => Quark.whenSettled() });

For one measurement inside a test, measureComplexity(engine) counts from that point: take() once the work has settled, stop() to restore the DOM, expectComplexity(budget) to match the test's complexity snapshot. Use it or trackComplexity in a file, not both: they share and reset the same counters.

const meter = measureComplexity(Quark.meter);
details.setAttribute("open", "");
await Quark.whenSettled();
const budget = meter.take();
meter.stop();
expectComplexity(budget);

A ComplexityBudget holds the engine counters (quarkRuns, ruleRuns, variableRuns, attributeRuns, listenerRuns, setVar, getVar, schedulePaint), the DOM calls (querySelectorAll, matches, closest, parentElement, parentNode, setAttribute, removeAttribute, textContent, importNode) and queryScopeCost, the elements scanned by the engine's rule queries, sampled at take(). parentElement and parentNode count the reads of each getter by the code under test, not the climbing the DOM emulation does to match a selector or build an event's path, which a browser does natively. Any engine with { counts, reset() } (EngineMeter) can be measured; without scopeSelectors(), queryScopeCost is 0. Quark.meter reads the selectors of the sheets registered at take(), so a sheet unregistered inside the measured window no longer counts there.

Headless Chrome

@excom/nucleus-test/chrome.mjs drives a page in headless Google Chrome from a Node script, for what happy-dom cannot show: layout, painted frames, a service worker. It needs Google Chrome on the machine, found in its usual place on macOS, Linux and Windows; CHROME overrides the path.

import { open, serve, until } from "@excom/nucleus-test/chrome.mjs";

const server = await serve({ root: "dist" });
const page = await open({ port: server.port });
await page.goto("/");
await until(() => page.run(() => !document.querySelector("[is-loading]")), 5000);
console.log(await page.run(() => document.title), page.issues());
await page.close();
server.close();
  • serve({ root?, port?, intercept? }) serves a directory (the working directory by default) on a free port, with index.html for an extensionless path without a file. intercept(url) sees each request first and answers it with { status, body, type }, or with nothing to decline
  • open({ port, size? }) opens a page. goto(pathOrUrl) loads it and waits until the network is quiet, run(fn, ...args) calls fn in the page with JSON arguments, cdp(method, params) sends a DevTools Protocol command, shot(name) saves a screenshot, issues() returns the console errors and warnings, exceptions and failed requests so far, close() ends Chrome. size is "390x844" by default; under 768 wide the page is mobile, with touch
  • until(check, ms) resolves true once check() is truthy, false after ms; sleep(ms) resolves after ms

Full documentation: https://nucleus.excom.dev/packages/nucleus-test