Skip to content

Commit e0acb08

Browse files
committed
feat: add basic test for emitter
1 parent 271c260 commit e0acb08

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

test/emitter.test.ts

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { Emitter } from "../src/common/emitter"
2+
3+
describe("emitter", () => {
4+
describe("Emitter", () => {
5+
it("should return an Emitter", async () => {
6+
const HELLO_WORLD = "HELLO_WORLD"
7+
const GOODBYE_WORLD = "GOODBYE_WORLD"
8+
const mockCallback = jest.fn(() => "Mock function called")
9+
const mockSecondCallback = jest.fn(() => undefined)
10+
11+
const emitter = new Emitter<{ event: string; callback: () => void }>()
12+
13+
const onHelloWorld = ({ event, callback }: { event: string; callback: () => void }): void => {
14+
if (event === HELLO_WORLD) {
15+
callback()
16+
}
17+
}
18+
19+
const onGoodbyeWorld = ({ event, callback }: { event: string; callback: () => void }): void => {
20+
if (event === GOODBYE_WORLD) {
21+
callback()
22+
}
23+
}
24+
25+
// Register the onHelloWorld listener
26+
// and the onGoodbyeWorld
27+
emitter.event(onHelloWorld)
28+
emitter.event(onGoodbyeWorld)
29+
30+
await emitter.emit({ event: HELLO_WORLD, callback: mockCallback })
31+
32+
// Double-check that our callback is called only once
33+
expect(mockCallback).toHaveBeenCalled()
34+
expect(mockCallback).toHaveBeenCalledTimes(1)
35+
36+
await emitter.emit({ event: GOODBYE_WORLD, callback: mockSecondCallback })
37+
38+
// Check that it works with multiple listeners
39+
expect(mockSecondCallback).toHaveBeenCalled()
40+
expect(mockSecondCallback).toHaveBeenCalledTimes(1)
41+
42+
// Dispose of all the listeners
43+
emitter.dispose()
44+
})
45+
46+
it.skip("should log an error if something goes wrong", () => {
47+
// not sure how we're going to test this
48+
// need to mock logger
49+
// and then somehow throw or something in the callback
50+
})
51+
})
52+
})

0 commit comments

Comments
 (0)