// @vitest-environment happy-dom /** * The sound check against a FAKE sound engine in a FAKE browser (happy-dom). This shows what the * page asks for and when; it says nothing about what a real phone, WebView or earbud does. */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { mountSoundCheck } from '../src/ui/soundCheck.ts'; /** True only while a click is being dispatched, like a browser's transient user activation. */ let pressing = false; type ResumeMode = 'gated' | 'rejects'; class FakeAudioContext { static instances: FakeAudioContext[] = []; static mode: ResumeMode = 'gated'; state: 'suspended' | 'running' = 'suspended'; currentTime = 0; destination = {}; /** Whether each resume() call was made during a press. */ resumeCalls: boolean[] = []; oscillators = 0; constructor() { FakeAudioContext.instances.push(this); } resume(): Promise { this.resumeCalls.push(pressing); if (FakeAudioContext.mode === 'rejects') return Promise.reject(new DOMException('not allowed here', 'NotAllowedError')); if (this.state === 'running') return Promise.resolve(); if (pressing) { this.state = 'running'; return Promise.resolve(); } // Blocked: like Chrome, the promise simply does not settle. return new Promise(() => {}); } createGain() { return { gain: { value: 1 }, connect: () => {} }; } createOscillator() { this.oscillators += 1; return { frequency: { value: 0 }, connect: () => {}, start: () => {}, stop: () => {} }; } } let speak: ReturnType; let enumerate: ReturnType; let fetchSpy: ReturnType; let storageSpy: ReturnType; let getUserMedia: ReturnType; let root: HTMLElement; function mount(): void { const win = { AudioContext: FakeAudioContext, setTimeout: (fn: () => void, ms: number) => setTimeout(fn, ms), speechSynthesis: { speak, getVoices: () => [] }, SpeechSynthesisUtterance: class { onend: (() => void) | null = null; onerror: (() => void) | null = null; constructor(public text: string) {} }, navigator: { mediaDevices: { enumerateDevices: enumerate, addEventListener: () => {}, getUserMedia } }, }; root = mountSoundCheck(document, win as unknown as Window); document.body.replaceChildren(root); } const button = (label: string) => [...root.querySelectorAll('button')].find((b) => b.textContent!.startsWith(label))!; const press = (b: HTMLButtonElement) => { pressing = true; try { b.click(); } finally { pressing = false; } }; const result = (key: string): string | undefined => { const dt = [...root.querySelectorAll('dt')].find((d) => d.textContent === key); return dt?.nextElementSibling?.textContent ?? undefined; }; const ctx = () => FakeAudioContext.instances[0]!; beforeEach(() => { vi.useFakeTimers(); FakeAudioContext.instances = []; FakeAudioContext.mode = 'gated'; pressing = false; speak = vi.fn(); getUserMedia = vi.fn(); enumerate = vi.fn(async () => [ { kind: 'audiooutput', label: 'Buds' }, { kind: 'audioinput', label: '' }, ]); fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response('')); storageSpy = vi.spyOn(Storage.prototype, 'setItem'); }); afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); }); describe('sound check (fake sound engine)', () => { it('on opening: no tone, no speech, no request, no storage, no microphone; reports that sound is blocked until a press', async () => { mount(); await vi.advanceTimersByTimeAsync(1000); expect(FakeAudioContext.instances).toHaveLength(1); expect(ctx().oscillators).toBe(0); expect(speak).not.toHaveBeenCalled(); expect(fetchSpy).not.toHaveBeenCalled(); expect(storageSpy).not.toHaveBeenCalled(); expect(getUserMedia).not.toHaveBeenCalled(); expect(result('Without touching the phone')).toBe('not allowed until a button here is pressed (suspended)'); expect(result('Outputs this page can see')).toBe('1: Buds'); expect(result('Test sound')).toBeUndefined(); expect(result('Delayed sound')).toBeUndefined(); // Still nothing a long time later. await vi.advanceTimersByTimeAsync(60_000); expect(ctx().oscillators).toBe(0); expect(speak).not.toHaveBeenCalled(); }); it('the delayed button, used first and alone, starts the engine during its own press and plays 20 s later', async () => { mount(); await vi.advanceTimersByTimeAsync(1000); const later = button('Play again in'); const before = ctx().resumeCalls.length; press(later); // resume() was called synchronously, inside the press. expect(ctx().resumeCalls.slice(before)).toEqual([true]); expect(later.disabled).toBe(true); await vi.advanceTimersByTimeAsync(0); expect(ctx().state).toBe('running'); expect(result('Delayed sound')).toMatch(/^waiting since .*lock the phone/); expect(ctx().oscillators).toBe(0); await vi.advanceTimersByTimeAsync(19_000); expect(ctx().oscillators).toBe(0); expect(later.disabled).toBe(true); await vi.advanceTimersByTimeAsync(1_100); expect(ctx().oscillators).toBe(2); expect(result('Delayed sound')).toMatch(/^played at /); expect(later.disabled).toBe(false); }); it('a delayed sound whose engine has stopped by the time it is due says so, and the button comes back', async () => { mount(); await vi.advanceTimersByTimeAsync(1000); const later = button('Play again in'); press(later); await vi.advanceTimersByTimeAsync(0); ctx().state = 'suspended'; // e.g. the page was put to sleep in the background await vi.advanceTimersByTimeAsync(21_000); expect(ctx().oscillators).toBe(0); expect(result('Delayed sound')).toMatch(/^blocked \(sound engine is suspended\) at /); expect(later.disabled).toBe(false); }); it('an engine that refuses to start is reported, nothing is scheduled, nothing is left unhandled', async () => { const unhandled = vi.fn(); // The client's tests are typed for a browser; the test runner itself is Node. const proc = (globalThis as unknown as { process: { on(e: string, f: () => void): void; off(e: string, f: () => void): void } }).process; proc.on('unhandledRejection', unhandled); try { FakeAudioContext.mode = 'rejects'; mount(); await vi.advanceTimersByTimeAsync(1000); const later = button('Play again in'); press(later); await vi.advanceTimersByTimeAsync(0); expect(result('Delayed sound')).toMatch(/^not started: blocked \(NotAllowedError: not allowed here\) at /); expect(later.disabled).toBe(false); await vi.advanceTimersByTimeAsync(30_000); expect(ctx().oscillators).toBe(0); expect(result('Delayed sound')).toMatch(/^not started: /); press(button('Play test sound')); await vi.advanceTimersByTimeAsync(0); expect(result('Test sound')).toMatch(/^blocked \(NotAllowedError: not allowed here\) at /); await vi.advanceTimersByTimeAsync(100); expect(unhandled).not.toHaveBeenCalled(); } finally { proc.off('unhandledRejection', unhandled); } }); it('the immediate test sound also starts the engine during its press', async () => { mount(); await vi.advanceTimersByTimeAsync(1000); const before = ctx().resumeCalls.length; press(button('Play test sound')); expect(ctx().resumeCalls.slice(before)).toEqual([true]); await vi.advanceTimersByTimeAsync(0); expect(ctx().oscillators).toBe(2); expect(result('Test sound')).toMatch(/^played at /); }); it('speech only on its button; output names stay on the page', async () => { mount(); await vi.advanceTimersByTimeAsync(1000); press(button('Speak with')); expect(speak).toHaveBeenCalledTimes(1); press(button('List outputs')); await vi.advanceTimersByTimeAsync(0); expect(enumerate).toHaveBeenCalledTimes(2); expect(fetchSpy).not.toHaveBeenCalled(); expect(storageSpy).not.toHaveBeenCalled(); expect(getUserMedia).not.toHaveBeenCalled(); }); });