-
Notifications
You must be signed in to change notification settings - Fork 2
/
MessageBus.test.js
97 lines (74 loc) · 2.34 KB
/
MessageBus.test.js
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
import tap from 'tap';
import MessageBus from '../src/MessageBus.js';
let bus;
tap.beforeEach(() => {
// Need to clear the global between tests for a clean slate
globalThis['@podium'] = null;
bus = new MessageBus();
});
tap.test('subscribe() - should be a function', (t) => {
t.ok(typeof bus.subscribe === 'function');
t.end();
});
tap.test('publish() - should be a function', (t) => {
t.ok(typeof bus.publish === 'function');
t.end();
});
tap.test('publish() - should invoke subscribed listener', (t) => {
const payload = { a: 'b' };
bus.subscribe('foo', 'bar', (event) => {
t.equal(event.payload, payload);
t.end();
});
bus.publish('foo', 'bar', payload);
});
tap.test('unsubscribe() - should remove subscribed listener', (t) => {
const channel = 'channel';
const topic = 'topic';
let cbCount = 0;
const callback = (event) => {
t.equal(event.channel, channel);
t.equal(event.topic, topic);
cbCount += 1;
};
bus.subscribe(channel, topic, callback);
bus.publish(channel, topic);
bus.publish(channel, topic);
t.equal(cbCount, 2, 'Callback function should have been invoked twice');
// Try unsubscribing and yet another publish
bus.unsubscribe(channel, topic, callback);
bus.publish(channel, topic);
t.equal(
cbCount,
2,
'Callback function was invoked even though we unsubscribed',
);
t.end();
});
tap.test('peek() - should initially be undefined', (t) => {
t.ok(bus.peek('channel', 'topic') === undefined);
t.end();
});
tap.test('peek() - should return latest event', (t) => {
const channel = 'channel';
const topic = 'topic';
for (let i = 0; i <= 3; i += 1) {
const event = bus.publish(channel, topic, i);
t.equal(event, bus.peek(channel, topic));
}
t.end();
});
tap.test('log() - should initially be empty', (t) => {
t.same(bus.log('channel', 'topic'), []);
t.end();
});
tap.test('log() - should retrieve earlier events, newest first', (t) => {
const channel = 'channel';
const topic = 'topic';
const payload1 = 'payload1';
const payload2 = { a: 'b' };
const event1 = bus.publish(channel, topic, payload1);
const event2 = bus.publish(channel, topic, payload2);
t.same(bus.log(channel, topic), [event2, event1]);
t.end();
});