/// import { assertEquals } from "jsr:@std/assert"; import { startServer } from "./deno.ts"; const hostname = "0.0.0.0"; const port = 8042; const href = `ws://${hostname}:${port}`; async function connect(url: string): Promise<[WebSocket, string[]]> { return new Promise((resolve) => { const messages: string[] = []; const socket = new WebSocket(url); socket.onmessage = ({ data }) => { messages.push(data); }; socket.onopen = () => resolve([socket, messages]); }); } function close(socket: WebSocket): Promise { return new Promise((resolve) => { if (socket.readyState === WebSocket.CLOSED) { return resolve(); } socket.onclose = () => resolve(); socket.close(); }); } function setup( fn: (ctx: Deno.TestContext) => Promise, ): (ctx: Deno.TestContext) => Promise { return async (ctx) => { const shutdown = startServer(hostname, port); try { await fn(ctx); } finally { await shutdown(); } }; } Deno.test( "broadcasts a message on connect to all clients", setup(async () => { const [s1, m1] = await connect(href); const [s2, m2] = await connect(href); assertEquals(m1, ["1 has joined!", "2 has joined!"]); assertEquals(m2, ["2 has joined!"]); await close(s2); await close(s1); }), ); Deno.test( "removes a client from broadcast after it disconnects", setup(async () => { const [s1, m1] = await connect(href); const [s2, m2] = await connect(href); const [s3, m3] = await connect(href); m1.length = 0; m2.length = 0; m3.length = 0; await close(s3); assertEquals(m1, ["3 has left!"]); assertEquals(m2, ["3 has left!"]); assertEquals(m3, []); await close(s2); await close(s1); }), );