forked from brendon1982/ts-mocking-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
06_PubSub.test.ts
53 lines (46 loc) · 1.55 KB
/
06_PubSub.test.ts
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
import { describe, it } from 'mocha'
import { default as sinon } from 'sinon'
import { expect } from 'chai'
import { PubSub } from '../tests-to-implement/06_PubSub'
describe('PubSub', () => {
describe('subscribe', () => {
it('calls subscription callback when publish occurs on channel', async () => {
// Arrange
const clock = sinon.useFakeTimers();
let sut = new PubSub();
let payloadSent = "";
sut.subscribe("channel1", (payload) => payloadSent = payload);
// Act
await sut.publish("channel1", "hello");
clock.tick(600);
// Assert
expect(payloadSent).eqls("hello");
})
it('calls all subscription callbacks when publish occurs on channel', async () => {
// Arrange
const clock = sinon.useFakeTimers();
let sut = new PubSub();
var callback1 = sinon.stub();
var callback1WasCalled = callBackWasCalled(callback1);
var callback2 = sinon.stub();
var callback2WasCalled = callBackWasCalled(callback2);
sut.subscribe("channel1", callback1);
sut.subscribe("channel1", callback2);
// Act
await sut.publish("channel1", "hello");
clock.tick(1000);
// Assert
await callback1WasCalled;
expect(callback1).calledWith("hello");
await callback2WasCalled;
expect(callback2).calledWith("hello");
})
async function callBackWasCalled(callback: sinon.SinonStub) {
return new Promise<void>((resolve => {
callback.callsFake((payload) =>
resolve()
)
}))
}
})
})