-
Notifications
You must be signed in to change notification settings - Fork 7
/
tinyPubSub.test.mjs
122 lines (101 loc) · 2.52 KB
/
tinyPubSub.test.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import * as tps from "./tinyPubSub.mjs";
describe("TinyPubSub (tps)", () => {
beforeEach(() => {
delete tps.pub.list;
});
describe("sub", () => {
it("should throw if anything that isn't a function is provided", () => {
const testCases = [void 0, "a", true, {}, []];
testCases.forEach((arg) => {
const type = {}.toString.call(arg);
expect(() => {
tps.sub(arg);
}).toThrow(
`To subscribe, a function must be provided: ${type} provided.`,
);
});
});
it("should allow subscriptions", () => {
const testFn1 = () => {};
expect(tps.pub.list).toBe(undefined);
tps.sub(testFn1);
expect(tps.pub.list.length).toBe(1);
});
});
describe("pub", () => {
it("should not error when no subscriptions exist", () => {
expect(tps.pub.list).toBe(undefined);
expect(tps.pub()).toBe(undefined);
});
it("should publish events to subscribers", () => {
let hasRun = false;
tps.sub(() => {
hasRun = true;
});
expect(hasRun).toBe(false);
tps.pub();
expect(hasRun).toBe(true);
});
it("should only publish to subscriptions; not removed subscriptions", () => {
const events = {
first: [],
second: [],
third: [],
fourth: [],
fifth: [],
};
const first = tps.sub((event) => {
events.first.push(event);
});
const second = tps.sub((event) => {
events.second.push(event);
});
const third = tps.sub((event) => {
events.third.push(event);
});
const fourth = tps.sub((event) => {
events.fourth.push(event);
});
tps.pub(0);
expect(events).toEqual({
first: [0],
second: [0],
third: [0],
fourth: [0],
fifth: [],
});
second();
tps.pub(1);
expect(events).toEqual({
first: [0, 1],
second: [0],
third: [0, 1],
fourth: [0, 1],
fifth: [],
});
const fifth = tps.sub((event) => {
events.fifth.push(event);
});
third();
tps.pub(2);
expect(events).toEqual({
first: [0, 1, 2],
second: [0],
third: [0, 1],
fourth: [0, 1, 2],
fifth: [2],
});
first();
fourth();
fifth();
tps.pub(3);
expect(events).toEqual({
first: [0, 1, 2],
second: [0],
third: [0, 1],
fourth: [0, 1, 2],
fifth: [2],
});
});
});
});