2021-03-11 22:28:18 +08:00
|
|
|
import PubSub from "../../js/lib/pub_sub";
|
|
|
|
|
|
|
|
describe("PubSub", () => {
|
|
|
|
test("subscribed callback is called on the specified topic", () => {
|
|
|
|
const pubsub = new PubSub();
|
|
|
|
const callback1 = jest.fn();
|
|
|
|
const callback2 = jest.fn();
|
|
|
|
|
2021-03-12 23:40:37 +08:00
|
|
|
pubsub.subscribe("topic1", callback1);
|
|
|
|
pubsub.subscribe("topic2", callback2);
|
|
|
|
pubsub.broadcast("topic1", { data: 1 });
|
2021-03-11 22:28:18 +08:00
|
|
|
|
|
|
|
expect(callback1).toHaveBeenCalledWith({ data: 1 });
|
|
|
|
expect(callback2).not.toHaveBeenCalled();
|
|
|
|
});
|
|
|
|
|
2021-05-07 22:41:37 +08:00
|
|
|
test("subscribe returns a function that unsubscribes", () => {
|
|
|
|
const pubsub = new PubSub();
|
|
|
|
const callback1 = jest.fn();
|
|
|
|
|
|
|
|
const unsubscribe = pubsub.subscribe("topic1", callback1);
|
|
|
|
unsubscribe();
|
|
|
|
pubsub.broadcast("topic1", {});
|
|
|
|
|
|
|
|
expect(callback1).not.toHaveBeenCalled();
|
|
|
|
});
|
|
|
|
|
2021-03-11 22:28:18 +08:00
|
|
|
test("unsubscribed callback is not called on the specified topic", () => {
|
|
|
|
const pubsub = new PubSub();
|
|
|
|
const callback1 = jest.fn();
|
|
|
|
|
2021-03-12 23:40:37 +08:00
|
|
|
pubsub.subscribe("topic1", callback1);
|
|
|
|
pubsub.unsubscribe("topic1", callback1);
|
|
|
|
pubsub.broadcast("topic1", {});
|
2021-03-11 22:28:18 +08:00
|
|
|
|
|
|
|
expect(callback1).not.toHaveBeenCalled();
|
|
|
|
});
|
|
|
|
});
|