-
Notifications
You must be signed in to change notification settings - Fork 1
/
eventEmitter.spec.js
62 lines (48 loc) · 1.56 KB
/
eventEmitter.spec.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
/* eslint-env jest */
const eventEmitter = require("./eventEmitter");
describe("Event Emitter", () => {
let emitter;
const callback1 = jest.fn();
const callback2 = jest.fn();
beforeEach(() => {
emitter = eventEmitter();
callback1.mockClear();
callback2.mockClear();
});
it("has simple API", () => {
const keys = Object.keys(emitter).sort().join();
expect(keys).toBe("emit,on");
});
it("passes data to registered callbacks", () => {
emitter.on("event", callback1);
emitter.on("click", callback2);
emitter.emit("event", "foo");
emitter.emit("click", "bar");
expect(callback1).toHaveBeenCalledTimes(1);
expect(callback1).toHaveBeenCalledWith("foo");
expect(callback2).toHaveBeenCalledTimes(1);
expect(callback2).toHaveBeenCalledWith("bar");
});
it("removes callback when it is unsubscibed", () => {
const unSub = emitter.on("event", callback1);
unSub();
emitter.emit("event", "foo");
expect(callback1).not.toHaveBeenCalled();
});
it("does not call a callback twice", () => {
emitter.on("event", callback1);
emitter.on("event", callback1);
emitter.emit("event", "foo");
expect(callback1).toHaveBeenCalledTimes(1);
expect(callback1).toHaveBeenCalledWith("foo");
});
it("does not leak on sucessfull emit", () => {
emitter.on("event", callback1);
const result = emitter.emit("event", "foo");
expect(result).toBeUndefined();
});
it("returns false on empty emit", () => {
const result = emitter.emit("event", "foo");
expect(result).toBe(false);
});
});