All files / src/test fakeSocket.ts

95.65% Statements 22/23
50% Branches 1/2
100% Functions 6/6
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44              6x 6x 6x 6x 6x   17x 17x 17x 17x 17x 17x   17x 17x 17x 17x 17x         18x       17x 17x 17x         5x      
/**
 * A stand-in for the browser's WebSocket, for pages that stream a chat turn
 * over one: it records what the page sends and opens as soon as the page has
 * listened. Install with `vi.stubGlobal("WebSocket", FakeSocket)` and reset
 * `FakeSocket.instances` per test.
 */
export class FakeSocket {
  static readonly CONNECTING = 0;
  static readonly OPEN = 1;
  static readonly CLOSING = 2;
  static readonly CLOSED = 3;
  static instances: FakeSocket[] = [];
 
  readyState: number = FakeSocket.CONNECTING;
  sent: string[] = [];
  onopen: (() => void) | null = null;
  onmessage: ((e: { data: string }) => void) | null = null;
  onerror: (() => void) | null = null;
  onclose: (() => void) | null = null;
 
  constructor(public url: string) {
    FakeSocket.instances.push(this);
    setTimeout(() => {
      this.readyState = FakeSocket.OPEN;
      this.onopen?.();
    }, 0);
  }
 
  send(data: string) {
    this.sent.push(data);
  }
 
  close() {
    Iif (this.readyState === FakeSocket.CLOSED) return;
    this.readyState = FakeSocket.CLOSED;
    this.onclose?.();
  }
 
  /** What the page sent, parsed. */
  frames(): Record<string, unknown>[] {
    return this.sent.map((s) => JSON.parse(s) as Record<string, unknown>);
  }
}