Skip to content

Commit a663956

Browse files
committed
feat: add timeout mechanism to WebSocket mock waitForConnection method
Prevents test hangs by adding a 5-second timeout to the waitForConnection method in WebSocketScenario. If a WebSocket connection doesn't open within the timeout period, the promise rejects with a descriptive error message. Changes: - Added timeout timer that rejects after 5 seconds - Proper cleanup of both timeout and polling interval on success - Switched from recursive setTimeout to setInterval for cleaner polling - Enhanced error message for timeout scenarios - Maintains backward compatibility with existing tests This ensures tests fail gracefully instead of hanging indefinitely when WebSocket connections fail to establish.
1 parent 9350dbf commit a663956

1 file changed

Lines changed: 29 additions & 10 deletions

File tree

tests/__utils__/websocket-mocks.ts

Lines changed: 29 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -328,19 +328,38 @@ export class WebSocketScenario {
328328
* Wait for WebSocket connection to be established
329329
*/
330330
private async waitForConnection(): Promise<void> {
331-
return new Promise((resolve) => {
331+
return new Promise((resolve, reject) => {
332332
if (this.mockWebSocket.isOpen()) {
333333
resolve();
334-
} else {
335-
const checkConnection = () => {
336-
if (this.mockWebSocket.isOpen()) {
337-
resolve();
338-
} else {
339-
setTimeout(checkConnection, 10);
340-
}
341-
};
342-
checkConnection();
334+
return;
343335
}
336+
337+
let timeoutId: NodeJS.Timeout | null = null;
338+
let intervalId: NodeJS.Timeout | null = null;
339+
340+
// Set up timeout to reject if connection doesn't open within 5 seconds
341+
timeoutId = setTimeout(() => {
342+
if (intervalId) {
343+
clearInterval(intervalId);
344+
}
345+
reject(new Error("WebSocket connection timeout: Connection did not open within 5 seconds"));
346+
}, 5000);
347+
348+
// Poll for connection with cleanup on success
349+
const checkConnection = () => {
350+
if (this.mockWebSocket.isOpen()) {
351+
if (timeoutId) {
352+
clearTimeout(timeoutId);
353+
}
354+
if (intervalId) {
355+
clearInterval(intervalId);
356+
}
357+
resolve();
358+
}
359+
};
360+
361+
// Start polling every 10ms
362+
intervalId = setInterval(checkConnection, 10);
344363
});
345364
}
346365
}

0 commit comments

Comments
 (0)