-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathlocal-stream.spec.ts
More file actions
404 lines (312 loc) · 13.5 KB
/
Copy pathlocal-stream.spec.ts
File metadata and controls
404 lines (312 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import { WebrtcCoreError } from '../errors';
import * as media from '.';
import { createMockedStream } from '../util/test-utils';
import { LocalStream, LocalStreamEventNames, TrackEffect } from './local-stream';
/**
* A dummy LocalStream implementation, so we can instantiate it for testing.
*/
class TestLocalStream extends LocalStream {}
describe('LocalStream', () => {
const mockStream = createMockedStream();
let localStream: LocalStream;
beforeEach(() => {
localStream = new TestLocalStream(mockStream);
});
describe('constructor', () => {
it('should add the correct event handlers on the track', () => {
expect.assertions(4);
const addEventListenerSpy = jest.spyOn(mockStream.getTracks()[0], 'addEventListener');
expect(addEventListenerSpy).toHaveBeenCalledTimes(3);
expect(addEventListenerSpy).toHaveBeenCalledWith('ended', expect.anything());
expect(addEventListenerSpy).toHaveBeenCalledWith('mute', expect.anything());
expect(addEventListenerSpy).toHaveBeenCalledWith('unmute', expect.anything());
});
});
describe('setUserMuted', () => {
let emitSpy: jest.SpyInstance;
beforeEach(() => {
localStream = new TestLocalStream(mockStream);
emitSpy = jest.spyOn(localStream[LocalStreamEventNames.UserMuteStateChange], 'emit');
});
it('should change the input track enabled state and fire an event', () => {
expect.assertions(8);
// Simulate the default state of the track's enabled state.
mockStream.getTracks()[0].enabled = true;
localStream.setUserMuted(true);
expect(mockStream.getTracks()[0].enabled).toBe(false);
expect(localStream.userMuted).toBe(true);
expect(emitSpy).toHaveBeenCalledTimes(1);
expect(emitSpy).toHaveBeenLastCalledWith(true);
localStream.setUserMuted(false);
expect(mockStream.getTracks()[0].enabled).toBe(true);
expect(localStream.userMuted).toBe(false);
expect(emitSpy).toHaveBeenCalledTimes(2);
expect(emitSpy).toHaveBeenLastCalledWith(false);
});
it('should not fire an event if the same mute state is set twice', () => {
expect.assertions(1);
// Simulate the default state of the track's enabled state.
mockStream.getTracks()[0].enabled = true;
localStream.setUserMuted(false);
expect(emitSpy).toHaveBeenCalledTimes(0);
});
});
describe('getSettings', () => {
it('should get the settings of the input track', () => {
expect.assertions(1);
const settings = localStream.getSettings();
expect(settings).toBe(mockStream.getTracks()[0].getSettings());
});
});
describe('stop', () => {
it('should call the stop method of the input track', () => {
expect.assertions(1);
const spy = jest.spyOn(mockStream.getTracks()[0], 'stop');
localStream.stop();
expect(spy).toHaveBeenCalledWith();
});
});
describe('addEffect', () => {
let effect: TrackEffect;
let loadSpy: jest.SpyInstance;
let emitSpy: jest.SpyInstance;
beforeEach(() => {
effect = {
id: 'test-id',
kind: 'test-kind',
isEnabled: false,
dispose: jest.fn().mockResolvedValue(undefined),
load: jest.fn().mockResolvedValue(undefined),
on: jest.fn(),
} as unknown as TrackEffect;
loadSpy = jest.spyOn(effect, 'load');
emitSpy = jest.spyOn(localStream[LocalStreamEventNames.EffectAdded], 'emit');
});
it('should load and add an effect', async () => {
expect.hasAssertions();
const addEffectPromise = localStream.addEffect(effect);
await expect(addEffectPromise).resolves.toBeUndefined();
expect(loadSpy).toHaveBeenCalledWith(mockStream.getTracks()[0]);
expect(localStream.getEffects()).toStrictEqual([effect]);
expect(emitSpy).toHaveBeenCalledWith(effect);
});
it('should load and add multiple effects with different IDs and kinds', async () => {
expect.hasAssertions();
const firstEffect = effect;
const secondEffect = {
...effect,
id: 'another-id',
kind: 'another-kind',
} as unknown as TrackEffect;
await localStream.addEffect(firstEffect);
await localStream.addEffect(secondEffect);
expect(loadSpy).toHaveBeenCalledTimes(2);
expect(localStream.getEffects()).toStrictEqual([firstEffect, secondEffect]);
expect(emitSpy).toHaveBeenCalledTimes(2);
});
it('should not load an effect with the same ID twice', async () => {
expect.hasAssertions();
await localStream.addEffect(effect);
const secondAddEffectPromise = localStream.addEffect(effect);
await expect(secondAddEffectPromise).resolves.toBeUndefined(); // no-op
expect(loadSpy).toHaveBeenCalledTimes(1);
expect(localStream.getEffects()).toStrictEqual([effect]);
expect(emitSpy).toHaveBeenCalledTimes(1);
});
it('should throw an error if an effect of the same kind is added while loading', async () => {
expect.hasAssertions();
const firstEffect = effect;
const secondEffect = { ...effect, id: 'another-id' } as unknown as TrackEffect; // same kind
const firstAddEffectPromise = localStream.addEffect(firstEffect);
const secondAddEffectPromise = localStream.addEffect(secondEffect);
await expect(firstAddEffectPromise).rejects.toBeInstanceOf(WebrtcCoreError);
await expect(secondAddEffectPromise).resolves.toBeUndefined();
expect(loadSpy).toHaveBeenCalledTimes(2);
expect(localStream.getEffects()).toStrictEqual([secondEffect]);
expect(emitSpy).toHaveBeenCalledTimes(1);
});
it('should replace the effect if an effect of the same kind is added after loading', async () => {
expect.hasAssertions();
const firstEffect = effect;
const secondEffect = { ...effect, id: 'another-id' } as unknown as TrackEffect; // same kind
await localStream.addEffect(firstEffect);
const secondAddEffectPromise = localStream.addEffect(secondEffect);
await expect(secondAddEffectPromise).resolves.toBeUndefined();
expect(loadSpy).toHaveBeenCalledTimes(2);
expect(localStream.getEffects()).toStrictEqual([secondEffect]);
expect(emitSpy).toHaveBeenCalledTimes(2);
});
it('should throw an error if effects are cleared while loading', async () => {
expect.hasAssertions();
const addEffectPromise = localStream.addEffect(effect);
await localStream.disposeEffects();
await expect(addEffectPromise).rejects.toBeInstanceOf(WebrtcCoreError);
expect(loadSpy).toHaveBeenCalledTimes(1);
expect(localStream.getEffects()).toStrictEqual([]);
expect(emitSpy).toHaveBeenCalledTimes(0);
});
});
describe('handleConstraintsRequired', () => {
const audioSettings: MediaTrackSettings = {
deviceId: 'test-device-id',
sampleRate: 48000,
channelCount: 1,
sampleSize: 16,
echoCancellation: true,
autoGainControl: true,
noiseSuppression: true,
};
let effect: TrackEffect;
let constraintsHandler: (constraints: MediaTrackConstraints) => Promise<void>;
let getUserMediaSpy: jest.SpyInstance;
let newAudioTrack: MediaStreamTrack;
beforeEach(async () => {
const inputTrack = mockStream.getTracks()[0];
jest.spyOn(inputTrack, 'getSettings').mockReturnValue(audioSettings);
const eventHandlers = new Map<string, (...args: unknown[]) => void>();
effect = {
id: 'nr-effect',
kind: 'noise-reduction',
isEnabled: false,
dispose: jest.fn().mockResolvedValue(undefined),
load: jest.fn().mockResolvedValue(undefined),
replaceInputTrack: jest.fn().mockResolvedValue(undefined),
on: jest.fn().mockImplementation((event: string, handler: (...args: unknown[]) => void) => {
eventHandlers.set(event, handler);
}),
off: jest.fn(),
} as unknown as TrackEffect;
const newMockStream = createMockedStream();
[newAudioTrack] = newMockStream.getTracks();
(newMockStream.getAudioTracks as jest.Mock).mockReturnValue([newAudioTrack]);
getUserMediaSpy = jest.spyOn(media, 'getUserMedia').mockResolvedValue(newMockStream);
await localStream.addEffect(effect);
constraintsHandler = eventHandlers.get('constraints-required') as (
constraints: MediaTrackConstraints
) => Promise<void>;
});
afterEach(() => {
getUserMediaSpy.mockRestore();
});
it('should call getUserMedia with old settings and effect constraints', async () => {
expect.hasAssertions();
await constraintsHandler({ autoGainControl: false, noiseSuppression: false });
expect(getUserMediaSpy).toHaveBeenCalledWith({
audio: {
deviceId: { exact: 'test-device-id' },
sampleRate: 48000,
channelCount: 1,
sampleSize: 16,
echoCancellation: true,
autoGainControl: false,
noiseSuppression: false,
},
});
});
it('should skip re-acquisition when constraints are empty and nothing saved', async () => {
expect.hasAssertions();
await constraintsHandler({});
expect(getUserMediaSpy).not.toHaveBeenCalled();
});
it('should skip re-acquisition when constraints are already satisfied', async () => {
expect.hasAssertions();
await constraintsHandler({ autoGainControl: true, noiseSuppression: true });
expect(getUserMediaSpy).not.toHaveBeenCalled();
});
it('should restore saved user constraints when empty constraints are received', async () => {
expect.hasAssertions();
await constraintsHandler({ autoGainControl: false, noiseSuppression: false });
getUserMediaSpy.mockClear();
(mockStream.getTracks as jest.Mock).mockReturnValue([newAudioTrack]);
jest.spyOn(newAudioTrack, 'getSettings').mockReturnValue({
...audioSettings,
autoGainControl: false,
noiseSuppression: false,
});
await constraintsHandler({});
expect(getUserMediaSpy).toHaveBeenCalledWith({
audio: expect.objectContaining({
autoGainControl: true,
noiseSuppression: true,
}),
});
});
it('should not restore a second time after saved constraints are cleared', async () => {
expect.hasAssertions();
await constraintsHandler({ autoGainControl: false });
getUserMediaSpy.mockClear();
(mockStream.getTracks as jest.Mock).mockReturnValue([newAudioTrack]);
jest.spyOn(newAudioTrack, 'getSettings').mockReturnValue({
...audioSettings,
autoGainControl: false,
});
await constraintsHandler({});
getUserMediaSpy.mockClear();
await constraintsHandler({});
expect(getUserMediaSpy).not.toHaveBeenCalled();
});
it('should replace the input track on the first effect', async () => {
expect.hasAssertions();
await constraintsHandler({ autoGainControl: false });
expect(effect.replaceInputTrack).toHaveBeenCalledWith(newAudioTrack);
});
it('should stop the old track', async () => {
expect.hasAssertions();
const oldTrack = mockStream.getTracks()[0];
const stopSpy = jest.spyOn(oldTrack, 'stop');
await constraintsHandler({ autoGainControl: false });
expect(stopSpy).toHaveBeenCalledWith();
});
it('should remove track handlers before stopping the old track', async () => {
expect.hasAssertions();
const oldTrack = mockStream.getTracks()[0];
const callOrder: string[] = [];
jest.spyOn(oldTrack, 'removeEventListener').mockImplementation(() => {
callOrder.push('removeEventListener');
});
jest.spyOn(oldTrack, 'stop').mockImplementation(() => {
callOrder.push('stop');
});
await constraintsHandler({ autoGainControl: false });
const firstRemove = callOrder.indexOf('removeEventListener');
const firstStop = callOrder.indexOf('stop');
expect(firstRemove).toBeGreaterThanOrEqual(0);
expect(firstStop).toBeGreaterThan(firstRemove);
});
it('should stop the old track before calling getUserMedia', async () => {
expect.hasAssertions();
const oldTrack = mockStream.getTracks()[0];
const callOrder: string[] = [];
jest.spyOn(oldTrack, 'stop').mockImplementation(() => {
callOrder.push('stop');
});
getUserMediaSpy.mockImplementation(async () => {
callOrder.push('getUserMedia');
const stream = createMockedStream();
(stream.getAudioTracks as jest.Mock).mockReturnValue(stream.getTracks());
return stream;
});
await constraintsHandler({ autoGainControl: false });
expect(callOrder).toStrictEqual(['stop', 'getUserMedia']);
});
});
describe('toJSON', () => {
it('should correctly serialize data', () => {
expect.assertions(1);
const testLocalStream = new TestLocalStream(mockStream);
const jsonLocalStream = localStream.toJSON();
const jsonTestLocalStream = testLocalStream.toJSON();
expect(JSON.stringify(jsonLocalStream)).toStrictEqual(JSON.stringify(jsonTestLocalStream));
});
it('should return an object with inputStream, outputStream and effects properties', () => {
expect.assertions(6);
const jsonLocalStream = localStream.toJSON();
expect(jsonLocalStream).toHaveProperty('muted');
expect(jsonLocalStream).toHaveProperty('label');
expect(jsonLocalStream).toHaveProperty('readyState');
expect(jsonLocalStream).toHaveProperty('inputStream');
expect(jsonLocalStream).toHaveProperty('outputStream');
expect(jsonLocalStream).toHaveProperty('effects');
});
});
});