Skip to content

Instantly share code, notes, and snippets.

@wowjeeez
Created April 8, 2024 17:37
Show Gist options
  • Save wowjeeez/0fc09fb54a8c57e5a3775087c1837b55 to your computer and use it in GitHub Desktop.
Save wowjeeez/0fc09fb54a8c57e5a3775087c1837b55 to your computer and use it in GitHub Desktop.
import { beforeEach, describe, expect, it, jest } from "@jest/globals";
import EventEmitter from "node:events";
import { ServerEventEngine } from "./event.engine";
import { block, SourceExtraData } from "@msfx/runtime";
describe("server event engine test", () => {
const serverEmitter = new EventEmitter();
const clientEmitter = new EventEmitter();
beforeEach(() => {
global.onNet = (eventName: string, handler: Function) =>
serverEmitter.on(eventName, handler as (...args: any[]) => void);
global.emitNet = (eventName: string, ...data: any[]) =>
clientEmitter.emit(eventName, ...data);
global.removeEventListener = (name: string, ref: Function) =>
serverEmitter.removeListener(name, ref as (...args: any[]) => void);
});
it("should bind an event listener and invoke it", async () => {
const engine = new ServerEventEngine();
const handlerFunction = jest.fn(async () => true);
engine.bindHandler("test", handlerFunction);
global.source = 1;
serverEmitter.emit("test", 0);
await block(100);
expect(handlerFunction).toHaveBeenCalledWith(1, 0);
});
it("should bind an event listener with layers and invoke it", async () => {
const engine = new ServerEventEngine();
const handlerFunction = jest.fn(async () => true);
const layerFunction = jest.fn(async (event, extra, data) => {
return {
success: true,
response: ["mock", extra] as [unknown, SourceExtraData]
};
});
engine.layer("test", layerFunction);
engine.bindHandler("test", handlerFunction);
global.source = 1;
serverEmitter.emit("test", 0);
await block(100);
expect(layerFunction).toHaveBeenCalledWith("test", 1, 0);
expect(handlerFunction).toHaveBeenCalledWith(1, "mock");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment