Rule 42 - JS: Unit tests and coverage
Every custom JavaScript file MUST be covered by a dedicated unit test file. Storybook interaction tests contribute coverage but are not a substitute for unit tests.
Rules
Tests are mandatory
42.1. Every JavaScript file under src/ MUST have a sibling
*.test.js file co-located in the same directory. A JS file without
a test file is a violation, regardless of coverage contributed
elsewhere.
vitest.config.js coverage.exclude carves out what declares rather
than executes - *.spec.js, *.stories.js, everything under
fixtures/ and the spec/ registry - plus the *.test.js files
themselves. A {name}.spec.js states a contract
the rule checks read, so it is covered through them rather than
through a test of its own.
This rule governs the design system. The lint step walks the trees TEST_INCLUDE in packages/cli/src/lib/file-collectors.js names - src/, .storybook/plugins/, packages/spec/src/, packages/cli/src/rules/, scripts/lib/ and the 3 dev-server launchers - so it also catches a missing test in the project's own tooling, but that code is outside src/ and Rule 42 does not govern its layout.
src/components/foo/foo.js ← implementationfoo.test.js ← REQUIRED - mandatory siblingfoo.twigfoo.cssfoo.stories.js
42.2. A JS file MUST NOT be merged without its *.test.js
sibling in the same commit.
100% line coverage
42.3. Every JS file covered by vitest.config.js coverage.include
MUST reach 100% line coverage. The project CI threshold
(CI_CODE_COVERAGE_THRESHOLD) MUST be set to 100.
42.4. Uncovered lines MAY be excluded using the v8 coverage
ignore directives, but ONLY when the code is structurally
unreachable in the test environment. Each ignore directive MUST
carry a short justification in the -- @preserve: <reason>
suffix.
/* v8 ignore next -- @preserve: CLI entrypoint - only runswhen invoked directly as a script. */if (import.meta.url === `file://${process.argv[1]}`) {main();}
42.5. Accepted v8 ignore directive forms:
/* v8 ignore next -- @preserve: <reason> */- skip the next statement./* v8 ignore next N -- @preserve: <reason> */- skip the next N lines./* v8 ignore start -- @preserve: <reason> */…/* v8 ignore stop -- @preserve */- skip a range./* v8 ignore if -- @preserve: <reason> *///* v8 ignore else -- @preserve: <reason> */- skip a branch./* v8 ignore file -- @preserve: <reason> */- skip an entire file (rare).
42.6. An ignore directive is a reviewed exception, not a budget to spend, so no global count gates it. Almost all shipped directives follow the thin-shim pattern from "When a test is too hard to write" - CLI entrypoints and filesystem orchestration exercised end-to-end by yarn lint - where the ignored range is glue around logic that is itself fully tested. Shipped runtime JS (src/**/*.js excluding *.util.js) is held to a stricter bar: a directive there marks a structurally unreachable defensive branch and stays rare. Reviewers SHOULD challenge every addition: if the line can be tested with a reasonable mock, test it.
Test file structure
42.7. Unit tests MUST run in Vitest's unit project, using the
node environment (no jsdom or happy-dom). DOM mocking MUST use
the shared harness in tests/support/: makeElement, makeEvent,
makeTextNode, parseHtml, matches, querySelector(All), and
listenerCount from tests/support/mock-dom.js, and setupDom /
fire from tests/support/mock-globals.js. A test file MUST NOT
hand-roll its own element factory, selector matcher, or globals
stubber.
import { listenerCount, makeElement, makeEvent } from '../../../tests/support/mock-dom.js';import { setupDom } from '../../../tests/support/mock-globals.js';
setupDom() stubs document, window, the three observers, the animation-frame pair, getComputedStyle, matchMedia, and the CustomEvent / Event constructors, and returns handles for driving them: body, head, documentElement, document, window, documentEvents, windowEvents, mutationObservers, intersectionObservers, resizeObservers, matchMedia, mediaQueries, canceledFrames, and flushAnimationFrames. Its options seed the initial document (readyState, currentScript, body, elements), the viewport (innerWidth, innerHeight), and the behavior stubs (media, computedStyle, deferAnimationFrames).
Globals only one or two components use -
localStorage, XMLHttpRequest, Intl, execCommand - are stubbed
by the test file itself, so the shared surface stays as narrow as the
components that share it.
The harness selector engine THROWS on any selector it cannot parse.
A gap is therefore a loud failure naming the file, never a silent
"no match" that lets a broken expectation pass. When a component
needs a selector the parser does not cover, extend the parser in
tests/support/mock-dom.js and add a case to its own test file -
do not work around it with a per-file matcher stub.
42.8. Tests MUST call vi.resetModules() and
vi.unstubAllGlobals() in beforeEach so each test starts from
a clean module cache and clean globals.
42.9. The module under test MUST be imported via
await import('./foo.js') inside the test body, AFTER setupDom()
has installed the globals. Per Rule 41.5, importing a component file
only registers it on window.Semetrika._registry - it does NOT
auto-init. Tests MUST also await import('../../boot.js') BEFORE
the component file so the _register / _collect helpers exist
when the component's IIFE runs, AND MUST then call
window.Semetrika.<name>.init(root) explicitly to exercise the
init path.
import { beforeEach, describe, it, expect, vi } from 'vitest';import { makeElement } from '../../../tests/support/mock-dom.js';import { setupDom } from '../../../tests/support/mock-globals.js';beforeEach(() => {vi.resetModules();vi.unstubAllGlobals();});describe('foo', () => {it('does the thing', async () => {const el = makeElement('div', { 'data-foo': '' });setupDom({ elements: [el] });await import('../../boot.js');await import('./foo.js');window.Semetrika.foo.init(document);// assertions on init() side effects});});Component tests MUST NOT mock
document.readyStateand dispatchDOMContentLoadedto trigger init - that lifecycle belongs tosrc/boot.jsand is covered bysrc/boot.test.js. Component tests exercise the component's owninit/destroydirectly.
42.10. Fixture files (sample SVGs, token CSS, markup snippets)
MUST live under a fixtures/ subdirectory inside the component
directory. The fixtures/ name is already excluded from
coverage and from the unit-test include list in vitest.config.js.
What tests MUST cover
42.11. Unit tests MUST cover, at minimum:
- The component's public init / setup path.
- Every
data-*attribute branch documented by the component. - Every keyboard interaction documented by the component.
- Disabled, invalid, and required state propagation where the component mirrors these from a source element.
- Mutation observer integration, for a module that owns an observer
of its own (a per-instance child observer or an attribute-filtered
observer per Rule 41.8) - the mutation it watches for MUST be
exercised. Modules that rely solely on
boot.js's bundle-level dispatch have no observer of their own to cover. - Bootstrap modes -
document.readyState === 'loading'deferral AND the already-completeimmediate path. This applies tosrc/boot.test.js, which owns that lifecycle; component tests MUST NOT cover it (see 42.9).
42.12. Unit tests MUST NOT rely on Storybook rendering or the
browser environment. A test that only passes inside Storybook is
an interaction test (play function in a *.stories.js file),
not a unit test.
Automated enforcement
42.13. A lint step MUST verify that every covered JS file has a
sibling *.test.js. CI fails when a new JS file is added without
a matching test file. The check is implemented in
packages/cli/src/rules/42.js (checkTestSiblings) and run as
part of yarn lint.
42.14. CI MUST enforce the 100% line-coverage threshold via the
CI_CODE_COVERAGE_THRESHOLD variable. A pull request that drops
coverage below 100% MUST fail.
Public API: init + destroy
42.15. Every shipped component/utility JS file MUST expose a
public API on window.Semetrika.<name> with both init and
destroy functions. init(root?) allocates the listeners,
observers, and timers the component needs. destroy(root?) tears
every one of them down, removes any DOM the script injected, and
clears the init marker so the element can be re-initialized.
The pair is published by passing it to _register per
Rule 41.5; src/boot.js assigns
window.Semetrika.<name>. A module MUST NOT assign it itself.
window.Semetrika._register('carousel', SELECTOR, init, destroy);
destroy() MUST be callable explicitly via the public API AND
reachable from boot.js's childList observer so removed nodes are
torn down automatically. Storybook interaction tests and unit tests
MUST exercise the destroy path.
When a test is too hard to write
If a test feels impossibly difficult to write, the code is likely doing too much. Before reaching for an ignore directive:
- Split the untestable orchestration (e.g. CLI wiring, global
bootstrap) from the pure logic. Put the pure logic in an
exported function; cover that function with unit tests; apply
/* v8 ignore start */only around the thin CLI shim. - If DOM interactions are complex, extend the shared harness in
tests/support/rather than introducingjsdomor adding a local mock. It already coverscreateElement,appendChild,cloneNode,classList,dataset, attribute reflection, inline style, HTML parsing and serialization, event dispatch with bubbling, and the observers - extend it once, and every suite gets the fix. - If an external library is involved (e.g.
@floating-ui/dom,twig), usevi.mock()to stub it with a minimal surface that your code exercises.
42.1, 42.13 by yarn cli 42 (checkTestSiblings in packages/cli/src/rules/42.js). 42.2-42.12, 42.14, 42.15 are review only. See enforcement.md.