DummySocket.ts 1.28 KB
import { expect } from "chai";
import {
  RawMessage,
  ServerOutboundMessage,
  ServerOutboundMessageKey,
  ServerResponse,
} from "../../../common";
import { SocketWrapper } from "../../connection/SocketWrapper";

export class DummySocket implements SocketWrapper {
  public handler?: (raw: RawMessage) => ServerResponse<any>;
  public disconnectHandler?: () => void;
  public receivedMessages: RawMessage[] = [];

  public setHandler(handler: (raw: RawMessage) => ServerResponse<any>) {}

  public setDisconnectHandler(handler: () => void) {}

  public send(raw: RawMessage): void {
    this.receivedMessages.push(raw);
  }

  private findMessageIndex<T extends ServerOutboundMessageKey>(key: T): number {
    for (let i = 0; i < this.receivedMessages.length; i++) {
      if (this.receivedMessages[i].type == key) {
        return i;
      }
    }
    return -1;
  }

  public received<T extends ServerOutboundMessageKey>(
    key: T
  ): ServerOutboundMessage<T> {
    const index = this.findMessageIndex(key);
    expect(index !== -1).eq(true);

    const message = this.receivedMessages[index];
    this.receivedMessages.splice(index, 1);
    return message.message;
  }

  public notReceived<T extends ServerOutboundMessageKey>(key: T): void {
    expect(this.findMessageIndex(key) === -1).eq(true);
  }
}