Skip to content

Commit

Permalink
Add mocks to test ampt events
Browse files Browse the repository at this point in the history
  • Loading branch information
tysoncadenhead committed Aug 6, 2024
1 parent 5844f85 commit 45578aa
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ampt-data-mock",
"version": "1.0.6",
"version": "1.1.0",
"description": "",
"main": "lib/index.js",
"scripts": {
Expand Down
33 changes: 33 additions & 0 deletions src/__tests__/events.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { events } from "../events";

describe("events", () => {
beforeEach(events.reset);

it("Should publish an event", () => {
const spy = jest.fn();
events.on("my.event", spy);
events.publish("my.event", { message: "Hello, World!" });

expect(spy).toHaveBeenCalledWith({
body: { message: "Hello, World!" },
name: "my.event",
});
});

it("Should ignore timeouts and config and just test the event", () => {
const spy = jest.fn();
events.on("my.event", { timeout: 10000 }, spy);
events.publish(
"my.event",
{
timeout: 1000,
},
{ message: "Hello, World!" }
);

expect(spy).toHaveBeenCalledWith({
body: { message: "Hello, World!" },
name: "my.event",
});
});
});
62 changes: 62 additions & 0 deletions src/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
let subscriptions = {};

interface EventHandlerEvent<BodyType = any> {
target: string;
id: string;
name: string;
body: BodyType;
time: number;
delay: number;
attempt?: number;
}

interface HandlerContext {
setTimeout(ms: number): void;
}

interface EventHandlerFunction<T = any> {
(event: EventHandlerEvent<T>, context: HandlerContext): void;
}

type StringNumberDate = string | number | Date;

interface Handler {
name: string;
callbacks: Array<Function>;
timeout: Number;
push(handler: Function): void;
setTimeout(ms: Number): void;
invoke(event: any, context: any): Promise<any[]>;
}

export const events = {
on: <T>(
event: string,
callbackOrConfig: EventHandlerFunction<T> | { timeout: number },
callback?: EventHandlerFunction<T>
): Handler | null => {
if (!subscriptions[event]) {
subscriptions[event] = [];
}

const callbackFn = callback || callbackOrConfig;
subscriptions[event].push(callbackFn);
return null;
},
publish: (
name: string,
eventOrConfig: { after: StringNumberDate } | any,
event?: any
) => {
const body = event || eventOrConfig;
if (!subscriptions[name]) {
return;
}
subscriptions[name].forEach((callback) => {
callback({ name, body });
});
},
reset: () => {
subscriptions = {};
},
};
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from "./data";
export * from "./events";

0 comments on commit 45578aa

Please sign in to comment.