Files
client/test/voice-capture.test.mjs
T

144 lines
5.5 KiB
JavaScript

// voice.js device and capture policy against stubbed DOM, Web Audio and getUserMedia (no real devices):
// a missing saved microphone never falls back to another one, a newly chosen device recovers capture only
// while capture is wanted, and a failed enumeration replaces the device menus' earlier list.
import test from 'node:test';
import assert from 'node:assert/strict';
const timeout = globalThis.setTimeout;
globalThis.setTimeout = (fn, ms, ...args) => {
const id = timeout(fn, ms, ...args);
id.unref?.();
return id;
};
class FakeNode {
constructor() {
Object.assign(this, { style: {}, dataset: {}, children: [], textContent: '', value: '', className: '' });
this.classList = { add() {}, remove() {}, toggle() {}, contains: () => false };
}
addEventListener() {}
removeEventListener() {}
setAttribute() {}
getAttribute() { return null; }
removeAttribute() {}
appendChild(child) { this.children.push(child); return child; }
replaceChildren(...children) { this.children = children; }
remove() {}
focus() {}
setPointerCapture() {}
querySelector() { return new FakeNode(); }
querySelectorAll() { return []; }
get firstElementChild() { return this.children[0] ?? new FakeNode(); }
}
const elements = new Map();
globalThis.Node = FakeNode;
globalThis.document = {
querySelector: (selector) => {
if (!elements.has(selector)) elements.set(selector, new FakeNode());
return elements.get(selector);
},
querySelectorAll: () => [],
createElement: () => new FakeNode(),
createElementNS: () => new FakeNode(),
createTextNode: () => new FakeNode(),
hasFocus: () => true,
documentElement: new FakeNode(),
};
globalThis.window = globalThis;
globalThis.addEventListener = () => {};
globalThis.requestAnimationFrame = () => 0;
const sent = [];
globalThis.teamspeach = { onAudio() {}, sendAudioFrame: (f) => sent.push(f), endAudio() {}, log() {} };
const calls = [];
const opened = [];
let enumerate = async () => [
{ kind: 'audioinput', deviceId: 'mic-2', label: 'Mic 2', groupId: 'g2' },
{ kind: 'audiooutput', deviceId: 'out-1', label: 'Out 1', groupId: 'g3' },
];
Object.defineProperty(globalThis, 'navigator', {
configurable: true,
value: {
mediaDevices: {
addEventListener() {},
enumerateDevices: () => enumerate(),
getUserMedia: async (constraints) => {
calls.push(constraints);
const id = constraints.audio.deviceId?.exact;
if (id === 'gone') throw Object.assign(new Error('Requested device not found'), { name: 'OverconstrainedError' });
const track = { label: id ?? 'default', muted: false, stopped: false, stop() { this.stopped = true; }, addEventListener() {}, getSettings: () => ({}) };
opened.push(track);
return { getTracks: () => [track], getAudioTracks: () => [track] };
},
},
},
});
const node = () => ({ connect: (next) => next, disconnect() {}, gain: { value: 1, setTargetAtTime() {} } });
globalThis.AudioContext = class {
constructor() {
Object.assign(this, { state: 'running', sampleRate: 48000, baseLatency: 0, currentTime: 0, destination: {} });
this.audioWorklet = { addModule: async () => {} };
}
createGain() { return node(); }
createMediaStreamSource() { return node(); }
async resume() {}
async setSinkId() {}
};
globalThis.AudioWorkletNode = class {
constructor() { Object.assign(this, node(), { port: { postMessage() {}, onmessage: null } }); }
};
const { S } = await import('../app/renderer/js/state.js');
const voice = await import('../app/renderer/js/voice.js');
S.prefs = { inputDeviceId: 'gone', outputDeviceId: '', echoCancellation: true, noiseSuppression: true, autoGainControl: true, transmitMode: 'open', pttCode: 'F8', voiceVolume: 100 };
voice.initVoice({ savePrefs: async (partial) => (S.prefs = { ...S.prefs, ...partial }) });
const connect = () => {
S.conn = { state: 'connected', address: 'x', reason: null };
S.snap = { clients: [], channels: [], own_client_id: 1, own_channel_id: 1 };
};
const disconnect = () => {
S.conn = { state: 'disconnected', address: '', reason: null };
S.snap = null;
};
test('a missing saved microphone fails closed: no other microphone is opened, nothing is sent', async () => {
connect();
await voice.syncCapture();
assert.equal(calls.length, 1);
assert.deepEqual(calls[0].audio.deviceId, { exact: 'gone' });
assert.equal(opened.length, 0);
assert.equal(voice.isCapturing(), false);
assert.equal(sent.length, 0);
});
test('choosing an available microphone after the failure recovers capture while connected', async () => {
await voice.chooseInputDevice('mic-2');
assert.equal(calls.length, 2);
assert.deepEqual(calls[1].audio.deviceId, { exact: 'mic-2' });
assert.equal(voice.isCapturing(), true);
assert.equal(opened.at(-1).label, 'mic-2');
});
test('while disconnected, choosing a microphone opens nothing', async () => {
disconnect();
await voice.syncCapture();
assert.equal(voice.isCapturing(), false);
assert.equal(opened.at(-1).stopped, true);
await voice.chooseInputDevice('mic-3');
assert.equal(calls.length, 2);
assert.equal(voice.isCapturing(), false);
});
test('a failed enumeration replaces the earlier device list for the menus', async () => {
const ok = await voice.deviceChoices();
assert.ok(ok.input.options.some((o) => o.value === 'mic-2'));
enumerate = async () => {
throw Object.assign(new Error('enumeration failed'), { name: 'NotReadableError' });
};
const failed = await voice.deviceChoices();
assert.deepEqual(failed, { error: { name: 'NotReadableError', message: 'enumeration failed' } });
assert.equal(failed.input, undefined);
});