1/* 2 * Copyright (C) 2025 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17import {TimeUtils} from 'common/time/time_utils'; 18import {UnitTestUtils} from 'test/unit/utils'; 19import {DevicesStream} from './devices_stream'; 20 21describe('DevicesStream', () => { 22 const dataListener = jasmine.createSpy(); 23 const errorListener = jasmine.createSpy(); 24 const testMessage = 'test'; 25 let stream: DevicesStream; 26 let webSocket: jasmine.SpyObj<WebSocket>; 27 28 beforeEach(() => { 29 webSocket = UnitTestUtils.makeFakeWebSocket(); 30 errorListener.calls.reset(); 31 stream = new DevicesStream(webSocket, dataListener, errorListener); 32 }); 33 34 afterEach(() => { 35 expect(errorListener).not.toHaveBeenCalled(); 36 }); 37 38 it('connects by setting data listener to onmessage', async () => { 39 let called = false; 40 dataListener.and.callFake(() => { 41 called = true; 42 }); 43 receiveMessage(); 44 expect(called).toBeFalse(); 45 await stream.connect(); 46 receiveMessage(); 47 await TimeUtils.wait(() => called); 48 expect(dataListener).toHaveBeenCalledOnceWith(testMessage); 49 }); 50 51 it('calls error listener on socket error', async () => { 52 webSocket.onerror!(new Event('error')); 53 expect(errorListener).toHaveBeenCalledTimes(1); 54 errorListener.calls.reset(); 55 }); 56 57 function receiveMessage() { 58 webSocket.onmessage!(UnitTestUtils.makeFakeWebSocketMessage('test')); 59 } 60}); 61