diff options
Diffstat (limited to 'web/test/fake-socket.ts')
| -rw-r--r-- | web/test/fake-socket.ts | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/web/test/fake-socket.ts b/web/test/fake-socket.ts new file mode 100644 index 0000000..290f9a8 --- /dev/null +++ b/web/test/fake-socket.ts @@ -0,0 +1,70 @@ +/** + * A scriptable fake WebSocket for the connection tests. It records outbound + * frames and lets tests drive `open` / `message` / `close` from either side. + */ +import type { Transport } from '$lib/protocol/connection'; + +export class FakeSocket implements Transport { + onopen: ((ev?: unknown) => void) | null = null; + onclose: ((ev?: unknown) => void) | null = null; + onerror: ((ev?: unknown) => void) | null = null; + onmessage: ((ev: { data: unknown }) => void) | null = null; + readyState = 1; // CONNECTING + + readonly sent: string[] = []; + closed = false; + + send(data: string): void { + if (this.readyState !== 0) throw new Error('not open'); + this.sent.push(data); + } + + close(): void { + if (this.closed) return; + this.closed = true; + this.readyState = 3; + this.onclose?.(); + } + + // test drivers -------------------------------------------------------- + + open(): void { + this.readyState = 0; + this.onopen?.(); + } + + /** Deliver a raw server frame. */ + serverSend(obj: object | string): void { + const data = typeof obj === 'string' ? obj : JSON.stringify(obj); + this.onmessage?.({ data }); + } + + /** The socket drops (server-side close). */ + serverClose(): void { + if (this.closed) return; + this.closed = true; + this.readyState = 3; + this.onclose?.(); + } + + lastJson(): Record<string, unknown> | null { + if (this.sent.length === 0) return null; + return JSON.parse(this.sent[this.sent.length - 1]); + } +} + +/** Creates and tracks a sequence of fake sockets handed to a connection. */ +export class SocketSequence { + readonly sockets: FakeSocket[] = []; + + // Arrow field so `this` survives being passed as a bare transport factory. + factory = (_url: string): Transport => { + const socket = new FakeSocket(); + this.sockets.push(socket); + return socket; + }; + + get current(): FakeSocket { + return this.sockets[this.sockets.length - 1]; + } +} |
