All files / rpc-calls/src/dispatcher/__tests__ MockServerWebSocketChannel.ts

47.61% Statements 10/21
33.33% Branches 3/9
20% Functions 3/15
50% Lines 10/20

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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71    1x 12x 12x 12x   12x                           11x 11x 11x                                                           1x 1x                                
import type {PhysicalChannelBase} from '@jsonjoy.com/channel';
 
export class MockServerWebSocketChannel implements PhysicalChannelBase<Uint8Array> {
  public closed = false;
  public onmessage: (data: Uint8Array, isUtf8: boolean) => void = () => {};
  public onclose: (code: number, reason: string) => void = () => {};
 
  public sentData: Uint8Array[] = [];
 
  public close(code?: number, reason?: string): void {
    this.closed = true;
    this.onclose(code ?? 1000, reason ?? 'CLOSE');
  }
 
  /**
   * Sends an outgoing message to the channel immediately.
   *
   * @param data A message payload.
   * @returns Number of bytes buffered or -1 if channel is not ready.
   */
  send(data: Uint8Array): number {
    Iif (this.closed) return -1;
    this.sentData.push(data);
    return data.byteLength;
  }
 
  public write(buf: Uint8Array): void {
    this.send(buf);
  }
 
  buffer(): number {
    return 0;
  }
 
  public sendPing(data: Uint8Array | null): void {
    // Mock implementation
  }
 
  public sendPong(data: Uint8Array | null): void {
    // Mock implementation
  }
 
  public sendBinMsg(data: Uint8Array): void {
    this.write(data);
  }
 
  public sendTxtMsg(txt: string): void {
    const data = new TextEncoder().encode(txt);
    this.write(data);
  }
 
  // Test helper methods
  public simulateMessage(data: Uint8Array, isUtf8: boolean = false): void {
    Eif (!this.closed) {
      this.onmessage(data, isUtf8);
    }
  }
 
  public getLastSentData(): Uint8Array | undefined {
    return this.sentData[this.sentData.length - 1];
  }
 
  public getAllSentData(): Uint8Array[] {
    return [...this.sentData];
  }
 
  public clearSentData(): void {
    this.sentData = [];
  }
}