fix(test): use dynamic port for websocket tests

This commit is contained in:
syntaxbullet
2026-01-07 13:37:21 +01:00
parent ac4025e179
commit 9c2098bc46
2 changed files with 8 additions and 13 deletions

View File

@@ -65,4 +65,7 @@ export class WebServer {
this.server = null; this.server = null;
} }
} }
public static get port(): number | undefined {
return this.server?.port;
}
} }

View File

@@ -14,18 +14,10 @@ describe("WebSocket Server", () => {
}); });
it("should accept websocket connection and send welcome message", async () => { it("should accept websocket connection and send welcome message", async () => {
// We need to know the actual port assigned by Bun if we passed 0. const port = WebServer.port;
// But WebServer stores it in private static server. expect(port).toBeDefined();
// We can't access it easily unless we expose it or use a known port.
// Let's rely on the fact that if we pass 0, we can't easily know the port without exposing it.
// So for this test, let's pick a random high port to avoid conflict: 40000 + Math.floor(Math.random() * 1000)
// Actually, let's restart with a known port 8081 for testing const ws = new WebSocket(`ws://localhost:${port}/ws`);
WebServer.stop();
const testPort = 8081;
WebServer.start(testPort);
const ws = new WebSocket(`ws://localhost:${testPort}/ws`);
const messagePromise = new Promise<any>((resolve) => { const messagePromise = new Promise<any>((resolve) => {
ws.onmessage = (event) => { ws.onmessage = (event) => {
@@ -41,13 +33,13 @@ describe("WebSocket Server", () => {
}); });
it("should reject non-ws upgrade requests on /ws endpoint via http", async () => { it("should reject non-ws upgrade requests on /ws endpoint via http", async () => {
const testPort = 8081; const port = WebServer.port;
// Just a normal fetch to /ws should fail with 426 Upgrade Required usually, // Just a normal fetch to /ws should fail with 426 Upgrade Required usually,
// but our implementation returns "WebSocket upgrade failed" 500 or undefined -> 101 Switching Protocols if valid. // but our implementation returns "WebSocket upgrade failed" 500 or undefined -> 101 Switching Protocols if valid.
// If we send a normal GET request to /ws without Upgrade headers, server.upgrade(req) returns false. // If we send a normal GET request to /ws without Upgrade headers, server.upgrade(req) returns false.
// So it returns status 500 "WebSocket upgrade failed" based on our code. // So it returns status 500 "WebSocket upgrade failed" based on our code.
const res = await fetch(`http://localhost:${testPort}/ws`); const res = await fetch(`http://localhost:${port}/ws`);
expect(res.status).toBe(500); expect(res.status).toBe(500);
expect(await res.text()).toBe("WebSocket upgrade failed"); expect(await res.text()).toBe("WebSocket upgrade failed");
}); });