SocketTester.ts 1.45 KB
import { expect } from "chai";
import {
  RawMessage,
  ServerInboundMessage,
  ServerInboundMessageKey,
  ServerResponse,
} from "../../../common";
import { Connection } from "../../connection/Connection";
import { RoomManager } from "../../room/RoomManager";
import { DummySocket } from "./DummySocket";

export class SocketTester {
  public readonly connection: Connection;
  public readonly socket: DummySocket;
  constructor(roomManager: RoomManager) {
    this.socket = new DummySocket();
    this.connection = new Connection(this.socket, roomManager);
  }

  public test<T extends ServerInboundMessageKey>(
    type: T,
    message: ServerInboundMessage<T>
  ): ServerResponse<any> {
    return this.connection.handleRaw({
      type: type as string,
      message: message,
    });
  }

  public testOk<T extends ServerInboundMessageKey>(
    type: T,
    message: ServerInboundMessage<T>
  ): void {
    expect(this.test(type, message).ok).eq(true);
  }

  public testNotOk<T extends ServerInboundMessageKey>(
    type: T,
    message: ServerInboundMessage<T>
  ): void {
    expect(this.test(type, message).ok).eq(false);
  }

  public testRaw(raw: RawMessage): ServerResponse<any> {
    return this.connection.handleRaw(raw);
  }

  public testAny(obj: any): ServerResponse<any> {
    return this.connection.handleRaw(obj);
  }

  public login(username: string): void {
    this.testOk("login", { username });
    expect(this.connection.user !== undefined).eq(true);
  }
}