2.5 KiB
setup/polyfills
(no submodules)
Purpose
The setup/polyfills module is a side-effect import that installs the globals test code expects to be present — crypto, TextEncoder, TextDecoder — when the host runtime (bare Node, happy-dom, jsdom, or Bun) doesn't already provide them. It's idempotent and safe to import multiple times.
Features
- Installs
globalThis.cryptofrom Node'swebcryptowhen missing - Installs
TextEncoder/TextDecoderfromnode:utilwhen missing - Guards every assignment with an existence check — never overwrites a populated global
- Exports nothing — side effects only
Usage: Basic Example
// vitest.config.ts
import { defineConfig } from "vitest/config";
import { createVitestConfig } from "@suaveplan/testing-dom/config";
export default defineConfig(
createVitestConfig(__dirname, {
setupFiles: ["@suaveplan/testing-dom/polyfills"],
})
);
Usage: Advanced Example
// bunfig.toml (bun-test)
// [test]
// preload = ["@suaveplan/testing-dom/polyfills", "./tests/install-matchers.ts"]
// Or programmatically via createBunTestConfig:
import { createBunTestConfig } from "@suaveplan/testing-dom/config";
const cfg = createBunTestConfig(__dirname, {
preload: ["./tests/install-matchers.ts"],
// createBunTestConfig adds the polyfills entry automatically.
});
API Reference
No exports. Side effects:
globalThis.crypto ??= webcrypto(fromnode:crypto)globalThis.TextEncoder ??= NodeTextEncoderglobalThis.TextDecoder ??= NodeTextDecoder
Implementation Notes
Modern Node (≥19) and Bun both ship crypto globally, so the ??= short-circuits on those hosts. The module remains in the package for older Node versions and for happy-dom sandboxes that don't initialise crypto. Imports use node: specifiers so the code remains bundler-safe — Rollup/esbuild skip it when externalising node built-ins. Because the module exports nothing, consumers who mistakenly try import { x } from "@suaveplan/testing-dom/polyfills" get a useful TypeScript error rather than silent misbehaviour.
Coverage
The polyfill bundle installs happy-dom's DOMParser, XMLSerializer, fetch, Request, Response, Headers, URL, URLSearchParams, and crypto.getRandomValues into the Node / Bun global scope when they are missing. Double-install is idempotent — the module tracks a Symbol.for("suaveplan.testing-dom.polyfilled") marker on globalThis so repeated imports are cheap.