diff --git a/src/renderer/api/__tests__/websocket-api.test.ts b/src/renderer/api/__tests__/websocket-api.test.ts new file mode 100644 index 0000000000..5dda62b60c --- /dev/null +++ b/src/renderer/api/__tests__/websocket-api.test.ts @@ -0,0 +1,37 @@ +/** + * Copyright (c) OpenLens Authors. All rights reserved. + * Licensed under MIT License. See LICENSE in root directory for more information. + */ + +import type { WebSocketEvents } from "../websocket-api"; +import { WebSocketApi } from "../websocket-api"; + +class TestWebSocketApi extends WebSocketApi { + flush(): void { + super.flush(); + } +} + +describe("WebsocketApi tests", () => { + let api: TestWebSocketApi; + + beforeEach(() => { + api = new TestWebSocketApi({}); + }); + + describe("before connection", () => { + it("does not hang when flush is called", () => { + api.flush(); + }); + + describe("when a message has been sent", () => { + beforeEach(() => { + api.send("a command"); + }); + + it("does not hang when flush is called", () => { + api.flush(); + }); + }); + }); +}); diff --git a/src/renderer/api/websocket-api.ts b/src/renderer/api/websocket-api.ts index 748fef5e7b..74c0e5067a 100644 --- a/src/renderer/api/websocket-api.ts +++ b/src/renderer/api/websocket-api.ts @@ -94,16 +94,8 @@ export class WebSocketApi extends (EventEmitter } } - protected getIsConnected(): this is (WebSocketApi & { socket: WebSocket }) { - return this.socket?.readyState === WebSocket.OPEN && this.isOnline; - } - - get isConnected() { - return this.getIsConnected(); - } - - get isOnline() { - return navigator.onLine; + isConnected(): this is (WebSocketApi & { socket: WebSocket }) { + return this.socket?.readyState === WebSocket.OPEN; } connect(url: string) { @@ -120,7 +112,7 @@ export class WebSocketApi extends (EventEmitter } ping() { - if (this.isConnected) { + if (this.isConnected()) { this.send(this.params.pingMessage); } } @@ -151,7 +143,7 @@ export class WebSocketApi extends (EventEmitter } send(command: string) { - if (this.getIsConnected()) { + if (this.isConnected()) { this.socket.send(command); } else { this.pendingCommands.push(command); @@ -159,11 +151,13 @@ export class WebSocketApi extends (EventEmitter } protected flush() { - for (const command of this.pendingCommands) { + const commands = this.pendingCommands; + + this.pendingCommands = []; + + for (const command of commands) { this.send(command); } - - this.pendingCommands.length = 0; } protected _onOpen(evt: Event) {