|
| 1 | +// waitFor semantics against a bare WebSocket server (no Chrome needed). |
| 2 | +// Test structure adapted from PR #111 by @MagMueller. |
| 3 | +import { afterAll, beforeAll, expect, test } from "bun:test" |
| 4 | +import { Session } from "../src/cdp/session" |
| 5 | + |
| 6 | +const channel = "cdp-events" |
| 7 | +const server = Bun.serve({ |
| 8 | + port: 0, |
| 9 | + fetch(req, srv) { |
| 10 | + return srv.upgrade(req) ? undefined : new Response("nope", { status: 400 }) |
| 11 | + }, |
| 12 | + websocket: { |
| 13 | + open(ws) { |
| 14 | + ws.subscribe(channel) |
| 15 | + }, |
| 16 | + message() {}, |
| 17 | + }, |
| 18 | +}) |
| 19 | +const session = new Session() |
| 20 | +const emit = (method: string, params: unknown) => { |
| 21 | + server.publish(channel, JSON.stringify({ method, params })) |
| 22 | +} |
| 23 | + |
| 24 | +beforeAll(async () => { |
| 25 | + await session.connect({ wsUrl: `ws://127.0.0.1:${server.port}/` }) |
| 26 | +}) |
| 27 | + |
| 28 | +afterAll(() => { |
| 29 | + session.close() |
| 30 | + server.stop(true) |
| 31 | +}) |
| 32 | + |
| 33 | +test("waitFor resolves on a matching event, respecting the predicate", async () => { |
| 34 | + const waiting = session.waitFor<{ ready: boolean }>("Test.event", { |
| 35 | + predicate: (params) => params.ready, |
| 36 | + timeoutMs: 1_000, |
| 37 | + }) |
| 38 | + emit("Test.event", { ready: false }) |
| 39 | + emit("Test.event", { ready: true }) |
| 40 | + expect(await waiting).toEqual({ ready: true }) |
| 41 | +}) |
| 42 | + |
| 43 | +test("waitFor honors timeoutMs", async () => { |
| 44 | + await expect(session.waitFor("Test.timeout", { timeoutMs: 20 })).rejects.toThrow("Timeout waiting for Test.timeout") |
| 45 | +}) |
| 46 | + |
| 47 | +test("waitFor rejects and unsubscribes when a predicate throws", async () => { |
| 48 | + let calls = 0 |
| 49 | + const waiting = session.waitFor("Test.bad", { |
| 50 | + predicate: () => { |
| 51 | + calls++ |
| 52 | + throw new Error("predicate failed") |
| 53 | + }, |
| 54 | + timeoutMs: 1_000, |
| 55 | + }) |
| 56 | + emit("Test.bad", {}) |
| 57 | + await expect(waiting).rejects.toThrow("predicate failed") |
| 58 | + emit("Test.bad", {}) |
| 59 | + await Bun.sleep(10) |
| 60 | + expect(calls).toBe(1) |
| 61 | +}) |
| 62 | + |
| 63 | +test("waitFor throws synchronously on the removed positional-predicate form", () => { |
| 64 | + // @ts-expect-error old signature: waitFor(method, predicate, timeoutMs) |
| 65 | + expect(() => session.waitFor("Test.positional", () => true, 1_000)).toThrow(TypeError) |
| 66 | +}) |
0 commit comments