Testing

TypeScript tests use Vitest and live under __tests__/ folders (see §3). Choose the smallest test boundary that observes the behavior at risk.


1. Philosophy

  • Unit tests by default. A pure transform needs input/output assertions with no collaborators. When the failure depends on a boundary, keep the real collaborators needed to observe it, including cross-module action routing, Automerge authority, history, or store projection. Double external seams such as hardware, OS I/O, and hosted services. Use the narrowest real path that would fail if the invariant broke.
  • Observe the outcome. Assert both the promised result and ownership or non-effects when they matter: an earlier revision must not overwrite a newer one, a late async completion must not revive retired state, and grouped undo must preserve unrelated edits. Control completion explicitly and await the resulting observable; do not rely on fixed microtask counts. For combinatorial invariants, use reproducible seeded property cases and retain a failing seed.
  • Unit-first. Playwright E2E lives under tests/e2e/. Run only affected specs with pnpm guard --profile broad -- pnpm test:e2e <spec>. Prefer Vitest for behavior observable below the browser; use an environment that actually renders audio, uses hardware, or hosts the full UI when that is the claim.
  • E2E files take test and expect from tests/e2e/e2eTest.ts. That module is the one place a per-test fixture reaches every test, so importing them from @playwright/test bypasses it; scripts/__tests__/e2eSharedTestFixture.spec.ts enforces the import. Type-only names still come from @playwright/test.
  • Ad-hoc live-UI probes. Keep one-off scripts and screenshots in the artifact workspace outside the checkout. Follow the lane setup and guarded execution steps in the Playwright UI bridge skill.
  • CI browser shards serve a production-mode build. The dev server's cold module transform is about half of all browser runner time, so a CI shard serves vite build --mode e2e through vite preview with one Playwright worker. A build serves no /src/... module URLs, so any file that loads one at runtime (itself, through a helper, or through an HTML probe) is listed in tests/e2e/devServerOnlySpecs.ts and runs against a dev server started in the same shard. Local runs, the offline smoke job, and nightly use the dev server throughout. A built shard runs a production React build, so a browser spec asserting zero console errors there cannot see React's development-only warnings; the dev-server runs still can. scripts/__tests__/e2eDevServerOnlySpecs.spec.ts fails when a file loads a /src/... URL without being listed, or stays listed after it stops.
  • Browser performance gates observe the product, not the runner. Main-thread work the product can split, defer or move off-thread keeps an absolute ceiling, such as the 50 ms long-task line: exceeding it is a product defect to fix by splitting the work. A single third-party operation the product cannot split is bounded against the same operation measured in the same page and run (a robust figure from several standalone samples, plus a stated margin, derived from measured shares and written beside the constant, for the work that has to share its task). Never gate a task with a bare wall-clock ceiling that it reaches only on a slower runner. That gate measures runner speed, and its failure points at no product change. Record every figure in the spec's attachment, and say in a comment which gates block and why.
  • Browser specs run with reduced motion. playwright.config.ts emulates prefers-reduced-motion: reduce, so decorative transitions do not add a fixed wait to every boot. The product must honour that preference wherever motion delays interaction, such as the launch overlay's exit. A spec that asserts a full-motion path opts back in with test.use({ reducedMotion: 'no-preference' }), as tests/e2e/launchFlows.spec.ts does for the launch fade.
  • Two reference hosts, no test-only privilege. Surfaces that have to hold in both hosts are proven in both. tests/e2e/agentWorkspace.spec.ts drives the agent workspace in the standalone browser — chat composer, Agent bottom tab, approval card, A/B comparison, revert — against an OpenAI-compatible endpoint on loopback admitted through configureCloudProvider. pnpm desktop:agent-proof (scripts/proveDesktopAgentWorkspace.ts, nightly only) drives the same flow in the packaged Electron app over the DevTools protocol, admitting the same endpoint through the Preferences AI form because the packaged renderer has no /src/... to import, and streaming one explain-mode answer back from it — as tests/e2e/aiConfirmApplyUndo.spec.ts does for the browser host — because admission alone is a local write and proves no round trip. Neither adds a hook, a test id, or a relaxed policy to the app or the preload: a proof that needs a privilege the product does not ship is proving something the product is not.
  • Specs follow the owner. Put each spec in __tests__/ inside the folder that owns the behavior. A source-matched name is the default for one subject; a named behavior spanning several subjects may have its own integration spec there. Do not place *.spec.ts beside production files.
  • Double only what the claim can exclude. A unit use-case test can replace repositories; a repository test can replace #/utils/desktopBridge or AudioContext. Keep real collaborators when their interaction is the subject. Mocks of Web Audio calls prove wiring and requested parameters, not rendered sound or latency.
  • Real domain types in tests. Event payloads and AppError values are constructed for real in tests. They are cheap, correct, and faking them hides bugs.

2. What we test, what we do not

Test:

  • Use cases — orchestration logic in useCases/
  • Repositories — all I/O, with their external dependency mocked
  • Transformers — pure mapping functions in transformers/
  • Services and validators — pure business logic in services/ and validators/
  • Stores — the custom Store<T> class and its backing storage
  • Event subscribers — files that call eventBus.on(...)
  • Engine classes — TrackNode, scheduler classes, anything in engine/, with AudioContext mocked
  • Presentation hooks — thin wrappers over useStore and similar
  • Presentation components — rendering + user interaction
  • Presentation helpers — pure utility functions

Use the environment required by the claim:

  • Real Automerge authority, history, and store projection belong in a focused Vitest test when their interaction is the obligation. A grouped undo with a later peer edit must replay the real group and inspect the raw document and projected state.
  • A rendered view may use a real store when the subscription or user-visible projection is the obligation. Isolate and restore that store for each test.
  • Native IPC round trips, rendered Web Audio output, timing, and hardware behavior need their actual host or a suitable dedicated harness. A fake bridge or AudioContext establishes only the calls it records. On the TS side, code review covers audio-thread constraints; crates/daw-dsp RT paths use assert_no_alloc.
  • Tests of the DI Container's lazy-proxy behavior are outside ordinary use-case tests; register dependencies before reading them.

3. File layout

Tests live in __tests__/ subfolders inside the folder that owns the code under test (same “concept” as the implementation: useCases, repositories, a presentation views segment, etc.).

Rule: For a single path/to/SourceFile.ts subject, default to path/to/__tests__/SourceFile.spec.ts. For a behavior spanning several subjects, name the spec after that behavior in the owning folder's __tests__/. Use *.spec.tsx for components.

Imports: From useCases/__tests__/addTrack.spec.ts, import the subject with a sibling-relative path — e.g. import { addTrack } from '../addTrack';.

Module-wide shared utilities (dummy factories, module-local mocks) live in src/modules/<Module>/__tests__/ at the module root and are imported from deeper specs with relative paths (e.g. ../../__tests__/TrackDummy).

Cross-module test utilities (mock AudioContext, shared helpers) live in src/helpers/__tests__/. DI and event runtime test helpers (not specs) live in src/infra/di/testing/ and src/infra/events/testing/.

Knip includes test files in the default project graph. Its Vitest plugin registers *.spec.* and *.test.* files as entry points automatically, so do not exclude them from project. The shipped src patterns in knip.json end with ! for production mode; the unsuffixed scripts pattern remains comprehensive-only. Dead-code audits are repository-wide and explicit-only. Run pnpm deps:unused or pnpm deps:unused:production after installing both dependency sets from the README setup.

src/modules/Arrangement/
├── __tests__/
│   ├── TrackDummy.ts              # module-wide dummy factory
│   ├── ClipDummy.ts
│   └── eventBus.mock.ts           # module-local mock (if needed)
├── useCases/
│   ├── __tests__/
│   │   ├── addTrack.spec.ts
│   │   └── removeTrack.spec.ts
│   ├── addTrack.ts
│   └── removeTrack.ts
├── repositories/
│   ├── __tests__/
│   │   └── trackTemplate.spec.ts
│   └── trackTemplate.ts
├── transformers/
│   ├── __tests__/
│   │   └── automationTransformers.spec.ts
│   └── automationTransformers.ts
└── presentations/
    └── hooks/
        ├── __tests__/
        │   └── useTracks.spec.ts
        ├── useTracks.ts
        └── useMoveClip.ts

Nested UI folders follow the same pattern (e.g. presentations/views/Mixer/__tests__/SendsSection.spec.tsx next to Mixer/SendsSection.tsx).


4. Naming convention

Every it block describes the behaviour under test concisely, using direct verb phrases or should/should not:

  • it('removes the track and emits TrackRemovedEvent')
  • it('should not emit when the store is empty')
  • it('throws InvalidTempoError when bpm is below 20')

5. Dependency injection in tests

The business layer uses the inject() DI pattern (see docs/architecture/03-typescript-module.md §4.11). Tests for injectable functions must use the companion test helpers rather than vi.mock():

  • inject(deps)(factory) — #/infra/di/inject — curried DI wrapper. The first call takes a dependency map, the second takes a factory that receives resolved deps. The wrapped function carries internal DI metadata used by the test seam.
  • injectDependencies(subject, mocks) — #/infra/di/testing/injectDependencies — calls Container.clear() and registers mocks against the subject's dependencies. Throws if a declared dependency is missing from mocks. Returns the subject for chaining.
  • spy<T>() — #/infra/di/testing/spy — creates a typed lazy spy. Every accessed method is a cached vi.fn() typed to the original signature; configure those mocks after access. The helper takes no overrides argument.

When to use which

Subject under testMock its deps with
An injectable (function wrapped in inject())spy<T>() + injectDependencies()
A module outside the inject map (#/utils/desktopBridge, etc.)vi.mock(modulePath, ...)
Thin static same-module repos used by an injectablevi.mock on those repo modules is OK when they are not in the inject map

Do not mix vi.mock() with injectDependencies() for the same dependency. Pick one.

Mocking a contract barrel

A vi.mock of another module's contract barrel (useCases, stores, events, presentations/views) whose factory lists every export by hand goes stale silently. Anything added to that barrel later resolves to undefined in this spec. For a view that means React throws on render, so every test in the mocking file reds — in a module the author's diff never touched. That is not hypothetical: adding MissingMediaPanel to Project/presentations/views took out all 13 tests in WorkspaceShell/…/TransportBar.spec.tsx.

Two shapes are correct, and the cheap one is first:

// 1. Name every export the spec's module graph actually imports from the barrel.
//    Costs nothing at import time — the factory still replaces the whole barrel.
//    Use this when the barrel is heavy, or when the point of the mock is that the
//    real module must not load (`src/app/__tests__/App.spec.tsx` is the example).
vi.mock('#/modules/Project/presentations/views', () => ({
    RecentProjectsMenu: () => <div data-testid="recent-projects" />,
    ArrangementSelector: () => <div data-testid="arrangement-selector" />,
    MissingMediaPanel: () => <div data-testid="missing-media-panel" />,
}));

// 2. Spread the original first, then override only what you stub. Later additions
//    resolve to the real export instead of `undefined`. This loads the real module
//    and its graph, so measure before using it on a heavy barrel — on
//    `ArrangeView.spec.tsx` the spread costs +75% wall time.
vi.mock('#/modules/Project/presentations/views', async (importOriginal) => ({
    ...(await importOriginal<typeof import('#/modules/Project/presentations/views')>()),
    RecentProjectsMenu: () => <div data-testid="recent-projects" />,
}));

What decides between them is faithfulness, not preference. A hand-listed stub must behave correctly for every name the tested path can reach: a factory that returns an Error, a type guard, a sentinel constant, or a journal write cannot be a bare vi.fn() standing in for it. When the spec does not intend to change that behaviour, shape 2 is the correct repair — spreading the real barrel keeps every untouched export faithful for free — rather than transcribing more names by hand to chase the drift.

pnpm test:barrel-mocks enforces this for presentations/views, stores, events, and useCases barrels: it walks each spec's module graph and fails when a non-spread factory omits a name that graph imports. No spec mocks an events contract barrel today — that kind is gated pre-emptively, not because it has been observed clean, so the tree's first events mock is caught by this gate the moment it goes stale rather than needing a later change to start checking it. Its focused guard spec covers the checker. The failure names the spec, barrel, missing export, and consuming module, then prints the three remedies, including a reasoned exemptions row in scripts/checkBarrelMockCoverage.ts — that row mutes only the export names it lists, not the whole (spec, barrel) pair, so a name outside the list still violates. --all is the same scan as the default gate now that every contract barrel kind is enforced. Background: PR #1572, issue #1393, #2364.

Canonical test shape for an injectable

// Pattern for Arrangement/useCases/publishTrackRemoved.ts:
// inject only ArrangementEventBus; thin repos stay static imports (often vi.mock'd).
import { describe, it, expect, vi } from 'vitest';
import { injectDependencies } from '#/infra/di/testing/injectDependencies';
import { publishTrackRemoved } from '../publishTrackRemoved';

describe('publishTrackRemoved', () => {
    it('should emit track.removed with the removed track id', async () => {
        const eventBus = { emit: vi.fn().mockResolvedValue(undefined) };
        injectDependencies(publishTrackRemoved, { eventBus });

        await publishTrackRemoved({ trackId: 'track-1' });

        expect(eventBus.emit).toHaveBeenCalledWith('track.removed', { trackId: 'track-1' });
    });
});

Notes on this shape:

  • injectDependencies mocks only the inject map keys (here eventBus). Static repo imports are mocked with vi.mock when needed.

6. How to test each layer

Every example below uses a real file from the codebase as its subject.

6.1 Use cases

Subject: src/modules/Arrangement/useCases/addTrack.ts — wrapped with inject(), reads a repo, writes the repo, emits an event.

Use the canonical shape from §5: spy<T>() + injectDependencies() for dependencies in the inject map. Do not vi.mock() an injected dependency; static repository imports may use the module mock shown above.

Use the canonical shape from §5 (and the real useCases/__tests__/addTrack.spec.ts in Arrangement). Do not invent TrackRepo / Logger inject deps that the subject does not declare.

6.2 Repositories — desktop IPC

Subject: src/modules/CrdtDocument/repositories/nativeCrdtPersistence/nativeCreateProject.ts — wraps the module's invokeCommand adapter.

Mock invokeCommand at the repository-folder boundary. Its own repository test covers the desktopInvoke call.

// src/modules/CrdtDocument/repositories/nativeCrdtPersistence/__tests__/nativeCrdtPersistence.spec.ts
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { invokeCommand } from '../invokeCommand';
import { nativeCreateProject } from '../nativeCreateProject';

vi.mock('../invokeCommand', () => ({
    invokeCommand: vi.fn(),
}));

describe('nativeCreateProject', () => {
    beforeEach(() => {
        vi.resetAllMocks();
    });

    it('should invoke collab_create_project with the given name and sample rate', async () => {
        vi.mocked(invokeCommand).mockResolvedValue(true);

        const result = await nativeCreateProject('My Project', 48000);

        expect(invokeCommand).toHaveBeenCalledWith('collab_create_project', {
            name: 'My Project',
            sampleRate: 48000,
        });
        expect(result).toBe(true);
    });

    it('should return false when the native layer returns null', async () => {
        vi.mocked(invokeCommand).mockResolvedValue(null);

        const result = await nativeCreateProject('My Project', 48000);

        expect(result).toBe(false);
    });
});

If the repository checks isDesktopRuntime() and short-circuits outside the desktop shell, also mock that helper (#/utils/desktopRuntime) and test both branches.

6.3 Repositories — Web Audio

Web Audio code is built on AudioContext and its node types. We provide a mock AudioContext factory (see §7.4) and assert on node wiring and parameter calls.

// src/modules/AudioEngine/repositories/__tests__/createWebAudioEngine.spec.ts
import { describe, it, expect, vi } from 'vitest';
import { createMockAudioContext } from '#/helpers/__tests__/audioContext.mock';
import { createWebAudioEngine } from '../createWebAudioEngine';

describe('createWebAudioEngine', () => {
    it('should connect the master gain node through the analyser to the destination', () => {
        const ctx = createMockAudioContext();
        // inject the mock context via whatever seam the repository exposes
        const engine = createWebAudioEngine({ context: ctx });

        expect(engine.masterGainNode.connect).toHaveBeenCalledWith(engine.masterAnalyser);
        expect(engine.masterAnalyser.connect).toHaveBeenCalledWith(ctx.destination);
    });
});

6.4 Repositories — storage-backed

For repositories that read/write through a Store<T>, swap the backing storage for MemoryStorage in the test. Do not mock Store itself — the class is small and well-tested in isolation (§6.7).

// src/modules/Arrangement/repositories/__tests__/trackTemplate.spec.ts
import { describe, it, expect, beforeEach } from 'vitest';
import { loadTrackTemplates, saveTrackTemplates } from '../trackTemplate';

describe('trackTemplate repository', () => {
    beforeEach(() => {
        // the repository uses LocalStorageStorage under the hood — for a true unit
        // test, inject a MemoryStorage via module refactor, or mock LocalStorageStorage
        localStorage.clear();
    });

    it('should return an empty array when nothing is saved', () => {
        expect(loadTrackTemplates()).toEqual([]);
    });

    it('should persist and retrieve templates', () => {
        const templates = [{ id: 't1', name: 'Drums' }];
        saveTrackTemplates(templates);
        expect(loadTrackTemplates()).toEqual(templates);
    });
});

If the repository is not designed to accept its storage by injection, that is a refactor to request, not a reason to write a worse test. Prefer injecting MemoryStorage at construction time.

6.5 Transformers

Subject: src/modules/Arrangement/transformers/automationTransformers.ts — pure math.

// src/modules/Arrangement/transformers/__tests__/automationTransformers.spec.ts
import { describe, it, expect } from 'vitest';
import { interpolateAutomationValue, generateShapePoints } from '../automationTransformers';

describe('interpolateAutomationValue', () => {
    it('should return the endpoint value when the requested beat equals p2.beat', () => {
        const p1 = { beat: 0, value: 0 };
        const p2 = { beat: 4, value: 1 };
        expect(interpolateAutomationValue(p1, p2, 4)).toBe(1);
    });

    it('should linearly interpolate halfway between two points', () => {
        const p1 = { beat: 0, value: 0 };
        const p2 = { beat: 4, value: 1 };
        expect(interpolateAutomationValue(p1, p2, 2)).toBeCloseTo(0.5);
    });
});

describe('generateShapePoints', () => {
    it('should build a two-point ramp for sawtooth-up between min and max', () => {
        expect(generateShapePoints('sawtooth-up', 0, 4, 0, 1)).toEqual([
            { beat: 0, value: 0, curve: 'linear', tension: 0 },
            { beat: 4, value: 1, curve: 'linear', tension: 0 },
        ]);
    });
});

No mocks. No beforeEach. Input in, output out.

6.6 Validators and services

Treat exactly like transformers — pure functions, no mocks, input/output assertions. One file per validator, one describe per exported function.

6.7 Stores (#/infra/store)

Subject: createStore / useStore under src/infra/store/.

Test the observable contract against the real factory: initial snapshot, set, subscribe/unsubscribe (and storage adapters if used). Prefer existing tests under src/infra/store/ as the pattern source over inventing a parallel Store class path.

6.8 Event subscribers

Files that wire a domain handler via eventBus.on(...). For a focused subscriber test, use createEventBus() from #/infra/events/createEventBus to create a real bus, wire one subscriber, then emit events and assert on its side effects. Do not cross product-module boundaries.

// src/modules/Toaster/useCases/__tests__/toasterSubscriber.spec.ts
import { describe, it, expect, vi } from 'vitest';
import { createEventBus } from '#/infra/events/createEventBus';
import type { AppEvents } from '#/app/registerDependencies';

describe('initToasterSubscribers', () => {
    it('should hydrate Toaster controls when audioDevice.loaded fires', async () => {
        const bus = createEventBus<AppEvents>();
        // wire up the subscriber with the test bus
        const unsubscribe = initToasterSubscribers(bus);

        await bus.emit('audioDevice.loaded', { deviceId: 'dev-1', deviceType: 'toaster' });

        // assert on the side effects (store updates, param calls, etc.)
        // ...

        unsubscribe();
    });
});

For unit-style tests using spies, build a spy with on and emit methods and inject it:

import { spy } from '#/infra/di/testing/spy';

const eventBus = spy<{ on: (event: string, handler: Function) => () => void }>();
// retrieve the registered handler from spy mock calls
const handler = eventBus.on.mock.calls[0][1];
handler({ deviceId: 'dev-1', deviceType: 'toaster' });

6.9 Presentation hooks

Subject: src/modules/Arrangement/presentations/hooks/useTracks.ts — thin wrapper over useStore reading trackStore.

For this hook's isolated mapping test, mock the store. Use @testing-library/react's renderHook. When subscription, projection, or action-to-view behavior is the obligation, use the real store and reset it between tests.

// src/modules/Arrangement/presentations/hooks/__tests__/useTracks.spec.ts
import { describe, it, expect, vi } from 'vitest';
import { renderHook } from '@testing-library/react';
import { useTracks } from '../useTracks';
import { trackStore } from '../../../stores/trackStore';
import { TrackDummy } from '../../../__tests__/TrackDummy';

vi.mock('../../../stores/trackStore', () => ({
    trackStore: {
        value: null,
        subscribe: vi.fn(() => () => {}),
    },
}));

describe('useTracks', () => {
    it('should return the default empty state when the store value is null', () => {
        vi.mocked(trackStore).value = null;

        const { result } = renderHook(() => useTracks());

        expect(result.current).toEqual({ tracks: [], selectedTrackId: null });
    });

    it('should return the stored tracks and selectedTrackId', () => {
        const track = TrackDummy.create();
        vi.mocked(trackStore).value = { tracks: [track], selectedTrackId: track.id };

        const { result } = renderHook(() => useTracks());

        expect(result.current.tracks).toEqual([track]);
        expect(result.current.selectedTrackId).toBe(track.id);
    });
});

6.10 Presentation components and views

Use @testing-library/react from the user's perspective.

  • Leaf components should not import useCases or business stores — pass props/callbacks from a view/hook, and test that surface (or pass mocked callbacks into the component).
  • Views/hooks may call use cases; mock them for presentation-only assertions, or keep the action and store path real when the user-visible interaction is the assertion.
// Prefer testing a view that owns the use-case call, or a component that receives onAddTrack:
// src/modules/Arrangement/presentations/components/__tests__/AddTrackButton.spec.tsx
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { AddTrackButton } from '../AddTrackButton';

describe('AddTrackButton', () => {
    it('should call the provided callback when clicked', () => {
        const onAddTrack = vi.fn();
        render(<AddTrackButton kind="audio" onAddTrack={onAddTrack} />);
        fireEvent.click(screen.getByRole('button', { name: /add audio track/i }));
        expect(onAddTrack).toHaveBeenCalled();
    });
});

6.11 Engine classes

Subject: src/modules/AudioEngine/engine/TrackNode.ts — constructs an audio graph from an AudioContext.

Pass a mock AudioContext (see §7.4) via the constructor deps. Assert on the node connections and parameter calls — these are the only observable outputs of the class until the audio thread runs.

Assert a parameter call's time only when the claim is timing, and then assert the frame it lands on, never the raw ctx.currentTime (.agents/skills/review-stances/audio-timing-format-laws.md probes 5 to 7). The clamp case below claims the value, so its time argument is expect.any(Number).

// src/modules/AudioEngine/engine/__tests__/TrackNode.spec.ts
import { describe, it, expect } from 'vitest';
import { TrackNode } from '../TrackNode';
import { createMockAudioContext } from '#/helpers/__tests__/audioContext.mock';
import { FADER_MAX_GAIN } from '#/utils/audioLevelLaw';

describe('TrackNode', () => {
    it('should wire gain → preFaderTap → fader → pan → analyser in order', () => {
        const ctx = createMockAudioContext();
        const node = new TrackNode('track-1', { context: ctx });

        expect(node.strip.gainNode.connect).toHaveBeenCalledWith(node.strip.preFaderTap);
        expect(node.strip.preFaderTap.connect).toHaveBeenCalledWith(node.strip.faderNode);
        expect(node.strip.faderNode.connect).toHaveBeenCalledWith(node.strip.panNode);
        expect(node.strip.panNode.connect).toHaveBeenCalledWith(node.strip.analyserNode);
    });

    it('should clamp gain to [0, FADER_MAX_GAIN] when setGain is called with out-of-range input', () => {
        const ctx = createMockAudioContext();
        const node = new TrackNode('track-1', { context: ctx });

        node.setGain(3);
        expect(node.strip.faderNode.gain.setTargetAtTime).toHaveBeenCalledWith(
            FADER_MAX_GAIN,
            expect.any(Number),
            0.01
        );

        node.setGain(-0.2);
        expect(node.strip.faderNode.gain.setTargetAtTime).toHaveBeenCalledWith(0, expect.any(Number), 0.01);
    });
});

7. Patterns

7.1 Dummy factories

Each module owns factories for its domain models in __tests__/. Factories accept a partial override and return a full, plausible instance.

// src/modules/Arrangement/__tests__/TrackDummy.ts
import type { Track } from '../models/Track';

let counter = 0;

export const TrackDummy = {
    create: (overrides?: Partial<Track>): Track => ({
        id: `track-${++counter}`,
        name: 'Test Track',
        kind: 'audio',
        color: '#ff0000',
        createdAt: new Date('2024-01-01T00:00:00Z'),
        ...overrides,
    }),
};

export const TracksDummy = {
    create: ({ length }: { length: number }): Track[] =>
        Array.from({ length }, (_, i) => TrackDummy.create({ id: `track-${i + 1}` })),
};

Use a deterministic counter for IDs, not Math.random. Tests should be reproducible.

7.2 EventBus spying

For injectables that depend on the event bus, build a local spy per test — no shared module-level mock is needed:

const eventBus = spy<{
    emit: (event: string, payload: unknown) => Promise<void>;
    on: (event: string, handler: Function) => () => void;
}>();
injectDependencies(subjectUnderTest, { eventBus /* other deps */ });

The spy gives you typed eventBus.emit and eventBus.on as Mocks directly. Retrieve registered handlers via eventBus.on.mock.calls[n][1] and invoke them to test subscriber behaviour (see §6.8).

Alternatively, use createEventBus() from #/infra/events/createEventBus for a focused EventBus contract or subscriber test, paired with recordEvents() from #/infra/events/testing/recordEvents to capture emitted events.

Subjects that need collaborators must be wrapped with inject() so tests can supply mocks via injectDependencies() (§5).

7.3 DI container and injectDependencies()

For injectables, use injectDependencies() (§5). It:

  1. Calls Container.clear() to reset container-backed state used by the DI layer.
  2. Validates that every key in the subject’s inject() dependency map has a matching mock.
  3. Registers each mock in the internal testOverrides map keyed by the original dependency reference (the same object identity the injectable uses in its map).
  4. Returns the subject for chaining.

Do not hand-manage Container in tests when testing inject()-wrapped functions — injectDependencies() is the single supported path.

If you must test code that resolves a class token via Container.get() (e.g. infra unit tests), use Container.clear() in afterEach and Container.register() / Container.set() as appropriate for that isolated test file — see src/infra/di/__tests__/Container.spec.ts.

7.4 AudioContext mock

Cross-module helper in src/helpers/__tests__/audioContext.mock.ts. It builds a fake AudioContext whose nodes expose spied connect/disconnect methods and typed AudioParam stubs.

// src/helpers/__tests__/audioContext.mock.ts
import { vi } from 'vitest';

const createAudioParam = () => ({
    value: 0,
    setValueAtTime: vi.fn(),
    setTargetAtTime: vi.fn(),
    linearRampToValueAtTime: vi.fn(),
    cancelScheduledValues: vi.fn(),
});

const createNode = (extra: Record<string, unknown> = {}) => ({
    connect: vi.fn(function (this: unknown, target: unknown) {
        return target;
    }),
    disconnect: vi.fn(),
    ...extra,
});

export function createMockAudioContext() {
    const destination = createNode();
    return {
        currentTime: 0,
        sampleRate: 48000,
        destination,
        createGain: vi.fn(() => createNode({ gain: createAudioParam() })),
        createStereoPanner: vi.fn(() => createNode({ pan: createAudioParam() })),
        createAnalyser: vi.fn(() =>
            createNode({
                frequencyBinCount: 1024,
                getByteTimeDomainData: vi.fn(),
                getFloatFrequencyData: vi.fn(),
            })
        ),
        createBufferSource: vi.fn(() =>
            createNode({
                buffer: null,
                playbackRate: createAudioParam(),
                start: vi.fn(),
                stop: vi.fn(),
            })
        ),
        createBuffer: vi.fn((channels: number, length: number, sampleRate: number) => ({
            numberOfChannels: channels,
            length,
            sampleRate,
            getChannelData: vi.fn(() => new Float32Array(length)),
        })),
        audioWorklet: { addModule: vi.fn().mockResolvedValue(undefined) },
        resume: vi.fn().mockResolvedValue(undefined),
        suspend: vi.fn().mockResolvedValue(undefined),
    };
}

Extend this as new node types are needed. Keep it flat and direct — this is a test helper, not a Web Audio polyfill.

7.5 Storage mocks

createStore accepts a storage option. Tests that need an isolated store should pass createMemoryStorage() (or the project’s memory storage helper) rather than inventing a mock class.

If a module’s store is a module-level singleton (e.g. export const trackStore = createStore(...)), tests may:

  1. Mock the whole store module (as in §6.9), or
  2. Call a reset helper exposed alongside the store that swaps its backing storage, or
  3. Use the real store with explicit per-test setup and cleanup when its behavior is part of the claim.

Prefer (1) for isolated mapping tests. Never let singleton state leak between cases.

7.6 Desktop runtime availability

Repositories that check isDesktopRuntime() before invoking a command need that check mocked:

vi.mock('#/utils/desktopRuntime', () => ({
    isDesktopRuntime: vi.fn(() => true),
}));

Test both branches: the desktop path (mock desktopInvoke) and the browser-only fallback path.


8. Rust testing

Rust unit tests live alongside source in #[cfg(test)] modules, per standard Rust convention.

Real example: crates/daw-dsp/src/grinder/engine.rs has a mod tests that builds a GrinderEngine, pushes a generated sine wave through process_block, and asserts on the output envelope.

Pattern: DSP signal-in / signal-out

#[cfg(test)]
mod tests {
    use super::*;

    fn process_sine(engine: &mut YourEngine, frequency: f32, samples: usize) -> Vec<f32> {
        let mut left = vec![0.0_f32; samples];
        let mut right = vec![0.0_f32; samples];
        for n in 0..samples {
            let phase = (n as f32 * 2.0 * std::f32::consts::PI * frequency) / 48_000.0;
            let sample = phase.sin() * 0.5;
            left[n] = sample;
            right[n] = sample;
        }
        engine.process_block(&mut left, &mut right);
        left
    }

    #[test]
    fn should_pass_signal_through_at_unity_gain() {
        let mut engine = YourEngine::new(48_000.0);
        engine.set_param("gain", 1.0);
        let output = process_sine(&mut engine, 220.0, 4096);
        let rms: f32 = (output.iter().map(|s| s * s).sum::<f32>() / output.len() as f32).sqrt();
        assert!((rms - 0.354).abs() < 0.01); // sine @ 0.5 amplitude → RMS ≈ 0.354
    }
}

Native command tests

Command bodies in crates/sourdaw-native/src/commands/ carry in-crate #[cfg(test)] coverage. Add command tests beside the Rust module they exercise; test the body directly rather than routing through the desktop shell's IPC.

Hosted effect WAV export

The hosted effect export spec requires macOS with a 44.1 or 48 kHz default audio output. Run it explicitly from the checkout you want to verify. It scans the harness CLAP effect in a disposable native profile and drives the mixdown dialog. The picker supplies a temporary destination and the native export transaction commits the WAV. The spec reads those file bytes and checks the stereo taps, the gain change, and the echo past the clip end against static-gain and zero-tail exports.

Choose an artifact directory outside the checkout on its drive. With dependencies installed, run:

export SOURDAW_HOSTED_EFFECT_EXPORT_ARTIFACTS=/absolute/path/to/hosted-effect-export
export SOURDAW_HOSTED_EFFECT_EXPORT_FIXTURES="$SOURDAW_HOSTED_EFFECT_EXPORT_ARTIFACTS/target/debug"
mkdir -p "$SOURDAW_HOSTED_EFFECT_EXPORT_ARTIFACTS"

pnpm guard --profile broad --show-output -- cargo build \
    --package sourdaw-native --lib --features napi-addon --package sourdaw-harness-fx \
    --target-dir "$SOURDAW_HOSTED_EFFECT_EXPORT_ARTIFACTS/target"
pnpm guard --profile focused --show-output -- cargo build \
    --package sourdaw-native --bin sourdaw-plugin-scan-helper \
    --target-dir "$SOURDAW_HOSTED_EFFECT_EXPORT_ARTIFACTS/target"
cp "$SOURDAW_HOSTED_EFFECT_EXPORT_FIXTURES/libsourdaw_native.dylib" \
    "$SOURDAW_HOSTED_EFFECT_EXPORT_FIXTURES/sourdaw-native.node"

pnpm guard --profile focused --show-output -- pnpm test:run \
    src/modules/AudioRendering/presentations/views/__tests__/hostedEffectExportSamples.integration.spec.tsx

The default unit run skips this hardware-dependent case. The focused run requires the configured binaries and fails if the render cannot use the native engine. It copies the three verified WAVs to the artifact directory. Auto-detect displays the plugin's reported tail, and the dialog's two-second minimum determines the Auto WAV length for this fixture.

Hosted browser quantum measurements

Changes to the browser quantum harness, its measured DSP closure, or the committed WASM it loads trigger quantum-measurements.yml. The workflow measures the complete reference project on a standard Ubuntu runner, checks the resulting JSON and Markdown against the checked-out pull-request head, and returns a one-day artifact containing those two data files, the raw log, and a receipt bound to the repository, pull request, head, run, and attempt. It never commits measurement data.

Treat the returned artifact as a candidate, not repository evidence. Before installing its JSON and Markdown, independently obtain the workflow run and artifact metadata, verify the receipt identity and file hashes, and compare the recorded source revision, source digests, and full device population with the clean consumer head. Failed runs produce no qualified artifact; their Actions log is diagnostic evidence and must not be retried unchanged into a passing record.


9. Running tests

CommandPurpose
pnpm test:watchVitest watch mode for active development
pnpm guard --profile focused -- pnpm test:run <target>Focused local run; pass the exact changed spec. PR CI owns the broader unit matrix
pnpm test:coverageFull Vitest coverage run; PR CI owns routine repository-wide validation
pnpm guard --profile broad -- pnpm test:e2e <spec>Focused local diagnostic; PR CI selects affected E2E specs. Bare command runs the full suite and is for explicit debugging only
pnpm guard --profile focused -- pnpm cargo:test --package <crate> <filter>Run affected Rust tests in debug mode

Run only checks affected by the changed files. Keep local verification focused on tests and formatting; CI owns lint, TypeScript typechecks, module boundaries, barrel-mock coverage, builds, and broad unit, Rust, and E2E suites. Use PR CI for those results; run a broader check locally only for an explicit, targeted debugging need. Run checks sequentially within each lane through package.json. Other lanes may validate concurrently when RAM permits. Wrap compute-heavy agent runs with pnpm guard --profile <p> [--max-rss-mib <estimate>] -- <command>. Estimate peak RAM from the latest observed guard peak or the nearest command; without an estimate the guard applies the profile ceiling, raised to the measured budget it records for known heavy scripts, and an RSS kill prints the budget it applied — record a budget above the observed peak in the guard's measuredScriptBudgets, never in a note. The guard reserves that budget and waits until measured free RAM covers active unused headroom, the new command, and the 2 GiB system reserve. It still enforces timeouts, process cleanup, host pressure, and the command RSS ceiling. Never bypass it.

Each guarded command inherits TMPDIR, TMP, and TEMP before startup, pointing to its own private directory under the primary repository's .agents/guard-storage/ on the repository's volume. Nested guards use separate directories and retain the shared memory admission registry. Normal exits, spawn errors, signals, and forced termination release storage only after the entire tracked process tree is proven stopped. A process that survives forced cleanup is a leak: it fails the run and records a guard-failure receipt that stops the lane. So is every storage verdict that names a cause rather than a lost proof: a census that proves a holder alive (such as a detached descendant with a working directory inside it), storage that is not private, denied or unusable inspection, a record the guard cannot read (the command deleted its own temp directory), and a release that throws. The first such census of a run is sticky: a later attempt that only hit the time bound never clears it, because the holder may still run. A leak records its final census in the receipt's census field, and pnpm guard --recover prints it. These never clear on their own and a later start cannot reclaim them, so reporting success would leave the directory forever. Only a census that could not finish a pass right now, with every diagnostic on the transient list in areTransientProofReasons (scripts/resourceGuardProofReasons.ts: a missed live process, an lsof catalog that lost a descriptor type, the census time bound, an unavailable ps list), after the tracked tree is proved exited, is retained without failing: the guard keeps the directory, prints one warning naming its path and the census reason, returns the command's own status, and records no receipt, because the lost proof says nothing about the work and keeping the files is the safe outcome. When the reclaim had already moved the payload under .claims/, the warning names that path and the retry resumes from the claim. Every later guarded start reclaims retained storage whose supervisor is dead once the census proves it free (recoverGuardStorage, run by createGuardStorage), and keeps what it still cannot prove. The guard never deletes old unowned system-temp caches. Before claiming or deleting storage, Unix command/environment census also vetoes removal when a process references its original temp path. This protects detached descendants that replace their environment and drop the session token. Argument references conservatively retain files too; they never grant authority to signal the matching process. Absence of those strings alone cannot prove storage abandoned. On macOS the guard also reads bounded lsof process/file fields; on Linux it reads same-account /proc cwd and file-descriptor links. Both the original temp path and any moved claim payload path veto reclamation while a process holds a working directory or open file there. An empty/unusable process census is unavailable monitoring evidence, and denied, malformed, truncated, or incomplete file evidence retains storage. On Linux, a descriptor that closes during inspection is checked with link and directory metadata. Reopening the descriptor directory can recreate the scanner's own closed slot and cannot prove that it remains open. A present slot or unavailable directory still retains storage. After a Linux ENOENT inspection failure, fresh complete status may prove file release only for a zombie whose PID and thread-group ID match the inspected PID, whose four UIDs match the guard, and whose thread count is exactly one. A zombie leader with other threads remains uncertain. This evidence must arrive within the existing proof deadline and never releases PID ownership or signaling fences. Denied inspection and unavailable or malformed status still retain storage, with one exception: a denied process whose /proc start time strictly precedes the supervisor that created the storage is excused. A live supervisor's start is read from /proc; recovery of an exited or crashed run, including a moved claim, compares against the /proc start ticks that supervisor recorded in its ownership record at creation. Ticks count from boot, so a record from an earlier boot can only excuse processes that cannot descend from it. A record without start ticks excuses nothing. Its start time proves only that the process inherited no working directory or descriptor from the run, not that it never opens the storage path later; an older same-account process explicitly handed that path is, like an elevated descendant, outside this proof. On macOS, an unreaped same-UID process positively sampled in zombie state has already released its file table; this exception never releases process-identity or signaling fences. File inspection checks same-UID process coverage again after reading files, so a process born during inspection cannot disappear from the proof. On Linux, a newly listed live same-UID process permits one complete replacement inspection of the full fresh process list, within at most two observations. On macOS, lsof races the processes it reads: a descriptor that closes between field reads leaves an otherwise valid catalog missing only its type, and a live same-UID process, whether newborn or already listed, can be absent from a whole-account catalog. Other work on a busy host keeps starting such processes, so a fresh whole catalog may never be complete. A missed process found gone after the observation's closing process list was taken, whether listed there and gone at its first liveness check, or found alive then and gone before its state sample or by its scoped read, never contributes to proof of release: it may have forked a storage user after that list, so the census takes a fresh whole observation, whose lists include any heir. An observation with such an exited process spends no scoped read. A missed process listed only in the opening list and gone at its first liveness check exited before the closing list, which therefore holds any child it forked, so it needs no fresh observation. A same-UID zombie needs no coverage, since XNU closes its file table first, but it may have forked before it became a zombie, so an observation with one still takes the closing parent list below. An omitted process with another or unsampled UID retains storage at once. Every other omitted process, in any sampled state including ps's undetermined ?, is read directly in the same observation with a PID-scoped, same-UID lsof: a storage path there is a live use; an exit status other than 0 or 1, any diagnostic, unusable output or a process that was not requested retains storage at once; a catalog missing only a descriptor type, or one that does not list a missed process, leaves it uncovered. A missed process read clean, or a skipped zombie, may already have handed storage to a new process, so before such an observation can prove release the census takes one closing same-UID process list with parents. A process absent from the observation's earlier lists whose parent is a missed process, including a zombie, another such newcomer, or launchd sends the census to a fresh whole observation; newcomers with other parents, and every other account's processes, are ignored so the census converges while other work starts processes. A process already listed and inspected that opens storage, or starts a storage user, afterwards remains outside this sampled proof. Coverage counts only within one observation and is never pooled across catalogs. An observation left uncovered, or a catalog missing a descriptor type, is discarded for a wholly fresh catalog and process list until one is covered or the five-second proof deadline expires; expiry retains storage with the last omission as its reason. Only wholly complete replacement evidence permits deletion; another uncovered process, ambiguous identity, malformed catalog, denied inspection or unavailable evidence retains storage. Processes created after the final proof remain outside that observation; this is conservative sampled evidence, not a guarantee of continuous isolation. Other Unix platforms without these file inspection APIs retain storage when proof is unavailable.

Automatic Unix reclamation covers the guard's own UID and requires private 0700 owned storage. Observed owned identities with another or uncertain UID retain storage. Privilege-changing or elevated descendants are outside this automatic proof: unrelated other-account processes cannot be inspected reliably without additional authority. No file-use match grants signal authority.

Required hosted Linux unit shards prepare a fresh unprivileged account before installing dependencies. A complete process census must show its numeric UID unused. The runner checkout stays unchanged. An independent mirror transport preserves its actual checked-out HEAD, complete history and refs in a fresh physical 0700 execution root under /var/tmp; shared objects and alternates are refused. Setup changes ownership only of opened physical directories inside this fresh root, preserving source files and external store inodes. The unit pnpm action installs its complete tool closure into an independent job directory under /var/tmp, without granting access to runner HOME or caches. The bootstrap uses npm ci --ignore-scripts against its reviewed official-registry lock. Its bundled get-pnpm downloader verifies the exact selected wrapper and native platform package signatures with pinned npm keys and verifies both tarball checksums before extraction. Setup checks the physical native executable's platform and architecture, then executes that file directly for its version before exporting PATH. Windows uses pnpm.exe directly. No lifecycle scripts, shell launchers, user config, or global package-manager installation participate in this trust path. Install and unit verification run through setpriv with cleared groups and capabilities, no_new_privs, an explicit environment, and private 0700 HOME, store and temporary directories. Before importing checkout source, stdlib admission validates all four UID/GID fields, source search/read access, and read/execute access to Node and the complete bounded pnpm closure. Escaping tool symlinks and unavailable access fail. Runtime admission repeats identity and private storage checks before pnpm; unavailable tools or authority fail the job. The account uses its own frozen-install store.

Before each required unit shard starts parallel workers, the admitted helper runs the whole scripts/__tests__/resourceGuardStorage.spec.ts, scripts/__tests__/resourceGuard.spec.ts, and scripts/__tests__/resourceGuardShowOutput.spec.ts sequentially through the zero-assertion wrapper, with one worker for each command. These real guard callers share conservative complete same-UID file-use proof: unrelated concurrent process transitions can make a later cleanup sample unavailable. Each command must finish successfully before the next starts. Failed or unavailable guard verification blocks the remaining commands and parallel shard with the original failure status. After success, the shard excludes exactly those three already-run files and keeps its normal worker setting. All other selected specs still run once across the four shards. The global shard exclusions stay unchanged.

No hosted Linux route runs those three files as the runner account. That account holds same-UID processes the guard cannot fully inspect, so the guard correctly retains the storage it creates there and each cleanup case reports a leak. The nightly unit shards therefore use the same fresh-account helper route as the required shards. The review tooling script suite excludes the three files: guard sources are not review tooling, so a head that changes them takes the broad profile and its isolated unit shards.

Before install or Vitest concurrency, mandatory native verification starts a nondumpable same-UID Python consumer with cwd and an open file in owned storage. It requires denied cwd inspection and actual storage retention, then kills and reaps the consumer and requires reclamation. Missing Python or uncertain cleanup fails preparation. This negative proof runs before workers because a denied same-account process conservatively blocks the cleanup of every guard whose supervisor started before it. Hosted account setup, tool traversal and checkout post-step compatibility require current-head Linux evidence; a local macOS port-controlled check cannot establish that acceptance.

New guard starts recover storage only after the supervisor and its descendants are proven dead. Records bind UUIDs, process start identities, and directory identities. Atomic rename claims let concurrent scavengers serialize one payload, and a claim retains its reclamation owner's identity outside that payload until deletion finishes, so a second supervisor crash remains recoverable. Live owners, reused or uncertain PID identities, malformed records, and symlinked ownership paths are retained. Windows normal cleanup uses its tracked-tree proof; detached, reparented descendants that drop the session token while retaining temp paths remain outside that platform's detection. Windows cannot establish a complete command/environment/file-use census after supervisor death, so crashed spawned runs there retain their storage for explicit inspection.

The guard samples available disk space on the system volume (/, or the SystemRoot drive on Windows) without walking its directory tree, because filling that volume freezes the machine; other volumes carry no reserve. It requires a 5 GiB free reserve at admission and throughout execution. Set --disk-reserve-mib <positive-integer> or SOURDAW_GUARD_DISK_RESERVE_MIB to configure it; nested guards inherit the chosen reserve. Supply the desired override again on --recover. Disk pressure during a run stops the process tree with the existing pressure failure receipt and a disk-specific diagnostic. Pressure at admission is a plain refusal with a non-zero exit and no receipt, since nothing ran; its message carries the cleanup guidance (delete only definite regenerable caches and agent junk, never anything a running process holds, report what was freed), which AGENTS.md deliberately omits. Unavailable or invalid disk sampling fails closed with monitor. Cleanup uncertainty never turns a stopped run into success.

A stopped pnpm dev command cannot prove recovery by exiting zero on its own. Supply an explicit finite proof after --, for example pnpm guard --recover --profile broad -- pnpm test:e2e tests/e2e/launchFlows.spec.ts. The guard runs that proof instead of replaying the server, from the receipt's canonical in-lane directory and under the receipt's profile unless --profile overrides it, as in that example; the memory budget resolves against the proof command itself, so a pnpm test:e2e proof runs under its measured budget unless --max-rss-mib overrides it. The proof is refused outright — exit 1 before anything spawns, leaving the receipt stopped — while the recorded origin already answers: the proof's own server cannot take an occupied port, so the run could only exercise the occupying server, which proves nothing about this checkout's recovery. Stop the occupying server and retry. The proof child receives the recorded port as SOURDAW_E2E_PORT and a freshly issued per-run token as SOURDAW_E2E_RUN_TOKEN — no proof file the command tree could fabricate, because the token only counts when a server stamps it, and the guard verifies the server directly. While the proof runs, the guard itself polls the recorded loopback origin and requires a response carrying this checkout's e2e marker AND this run's token before it clears the unchanged original receipt; the token binds the observation to the run, so a leftover e2e server that binds after the unserved-origin check stamps the checkout root but no (or a stale) token and cannot satisfy the watch. What the guard can prove is that a server this proof started answered at the recorded origin; what it cannot prove is that the browser suite exercised the app — the proof's own exit code covers that. The guard still owns resource enforcement and process-tree cleanup. An unrelated command's zero exit, an unmarked or foreign server at the recorded origin, a failed proof, signal, timeout, resource stop, cleanup leak, or concurrently replaced receipt preserves the stop. Explicit proofs require a recorded pnpm dev, pnpm run dev, or literal node scripts/e2eDevServer.ts PORT receipt. The node launcher requires the lane root as its recorded cwd, a canonical script path belonging to that lane, and exactly one explicit decimal port from 1 through 65535; missing ports never use the current environment. Other scripts, including dev:no-hmr, and extra node arguments are ineligible. Explicit proofs cannot be combined with lint-target replacement; ordinary --recover replay is unchanged.

Existing running commands and old lane copies keep their original guard. After this change lands, their next verification must invoke the updated guard, or merge the fix into the owned lane when needed. Do not rewrite or clean another agent's lane to upgrade it. To use an approved updated checkout without changing the stopped lane, invoke that checkout's scripts/resourceGuard.ts by absolute path with node, keeping the stopped lane as the working directory and passing --recover -- <finite-proof-command>; lane detection, dependency preflight, recorded cwd and receipt ownership still come from the stopped lane.

Vitest config is in vite.config.ts (test and test.coverage blocks). Global setup is src/setupTests.ts, which loads @testing-library/jest-dom. Coverage uses @vitest/coverage-istanbul.

CI owns lint and all TypeScript typechecks, including the spec-inclusive tsconfig.test.json check. Do not run lint or typecheck commands locally; use the pull request's CI results as their verification evidence. When you touch a spec, dummy factory, or model shape mirrored by fixtures, keep fixtures aligned with the real types and never silence errors with any or @ts-expect-error.


10. Anti-patterns

Do not:

  • Use a broad integration fixture without an observable reason. Keep only the cross-module route required for the invariant. Use Playwright when the browser interaction itself matters.
  • Claim rendered audio or latency from an AudioContext mock. The mock from §7.4 proves wiring and calls only; use a rendering or hardware environment for audible output and timing claims.
  • Mock event payloads or AppError values. They are cheap plain objects. Construct them for real.
  • Write React Query tests. This codebase does not use TanStack Query for core state — state flows through Store<T>.
  • Depend on real time. No setTimeout in tests, no real AudioContext.currentTime, no real Date.now() assertions. Use fake timers (vi.useFakeTimers()) or explicit values.
  • Share mutable state between tests. Every test sets up its own dummies, its own mocks, its own store instances. beforeEach resets.
  • Rely on the Container's lazy proxy. Tests run in strict mode — Container.get() throws on missing tokens. Use injectDependencies or register your fakes explicitly.
  • Cast spy methods to Mock. If you find yourself writing (spyObject.method as unknown as Mock).mockReturnValue(...), the subject isn't using spy<T>(). Rebuild the spy with spy<T>() so method types carry Mock natively.
  • Forget a mock in injectDependencies. The helper throws if you do — don't disable the check. Every dep gets a mock, even the ones you "don't care about" (use spy<T>() with no overrides for those).
  • Snapshot-test dynamic UI. Snapshots are for stable, literal structure. If a component renders varying content, assert on the content explicitly.
  • Leak mocks across files. Module-level vi.mock(...) is scoped to its spec file — but be disciplined and don't rely on test-file ordering.

Required pull-request scope and nightly coverage

Gate requires validation, the affected browser plan, its selected E2E workflows and hardware proof, and applicable CodeQL execution. The aggregate and its assertion step always run, including after cancellation, and reject cancelled or unexpectedly skipped dependencies. Every non-draft pull request runs that full path. A draft fails Gate without the heavy jobs, because a skipped required check would pass.

The deterministic selector in scripts/prValidationScope.ts reads the complete Git diff between immutable base/head revisions, including both rename paths. It publishes pr-validation-scope with the selected files and reasons. Product changes run the offline smoke set and complete browser suite with hardware admission, including presentation files, shared application code, test helpers, dependencies, deleted browser tests and unknown paths. Changed E2E specs run directly. Documentation and known review tooling avoid browser execution. Vitest-collected spec files under src/ keep broad non-browser validation without browser execution, since the browser never loads them; non-spec files under __tests__/ stay on the product route. The same affected profile reaches validation: a documentation-only pull request runs the standing static and security jobs; explicitly known review tooling also runs script types, lint, the script unit suite and review contracts. Application builds, application unit shards, browser jobs and native checks require a product or unclassified change. Unknown scripts, build configuration and mixed product changes keep broad coverage. A forced full validation run and the nightly retain their full scope. An AI judgment cannot waive deterministic coverage. Missing selected files and malformed plans fail. Selected browser files split into at most twelve shards by recorded duration: longest file first, each into the shard with the least recorded time, so one slow shard does not hold Gate. Durations live in scripts/e2eSpecDurations.json, refreshed from a green full run by the command its module documents; a file without a recording weighs as the median file. CodeQL runs for JavaScript/TypeScript and relevant workflow or security configuration changes; the PR secret scan and dependency review remain in required validation even when CodeQL is skipped.

Required PR unit coverage

The four isolated PR unit shards run the existing test suite with Istanbul coverage. Istanbul instruments production sources selectively so test helpers, dependencies and compiler tooling run without coverage instrumentation. The coverage job checks all four reports belong to the current run attempt and tested revision, merges them into one production report and contributes its result to the required Gate. The unit coverage artifact contains the HTML report, exact covered/total counts, the uncovered changed file and line list in gate.json, and shard wall-clock durations.

Coverage applies to production TypeScript and TSX under src/. It excludes declarations, test specs and test helpers, the test setup and the app bootstrap entry point. The coverage configuration includes files the shards never import. The PR must cover at least 90% of changed executable lines, counted once each using Istanbul statement-start line coverage. The diff uses the tested integration commit and its first parent, so reported lines match the tested tree even when the base advances. A change without executable lines has an explicit zero-line result. If Istanbul omits a file, the gate verifies that its tested Git blob has no Istanbul-instrumentable body. It permits an empty body, static import and export declarations, and empty undecorated classes without a base class. A missing executable file or shard fails the check.

The overall floors for lines, statements, branches and functions live in scripts/unitCoverageFloors.json. They are measured from the merged report, in hundredths of a percentage point rounded down. The gate compares exact counts to these floors and rejects any proposed decrease against the tested base. The initial floors come from the hosted unit suite's measured baseline. To raise them, review measured-floors.json in the unit coverage artifact and commit the desired increases. A successful change must meet the proposed floors as well as the changed-line minimum.

The nightly keeps the full E2E matrix, Browser AI hardware admission, platform and desktop proofs, full-history secret scan and security analysis. Production deployment remains downstream of that full successful train. Scoped PR coverage supplements rather than replaces this full-load gate.