Skip to content

Commit 33d4ba9

Browse files
committed
feat: add test for catching errors in Emitter
1 parent a2e4e60 commit 33d4ba9

File tree

1 file changed

+40
-4
lines changed

1 file changed

+40
-4
lines changed

test/emitter.test.ts

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,25 @@
1+
// Note: we need to import logger from the root
2+
// because this is the logger used in logError in ../src/common/util
3+
import { logger } from "../node_modules/@coder/logger"
4+
15
import { Emitter } from "../src/common/emitter"
26

37
describe("emitter", () => {
48
describe("Emitter", () => {
9+
let spy: jest.SpyInstance
10+
11+
beforeEach(() => {
12+
spy = jest.spyOn(logger, "error")
13+
})
14+
15+
afterEach(() => {
16+
jest.clearAllMocks()
17+
})
18+
19+
afterAll(() => {
20+
jest.restoreAllMocks()
21+
})
22+
523
it("should return an Emitter", async () => {
624
const HELLO_WORLD = "HELLO_WORLD"
725
const GOODBYE_WORLD = "GOODBYE_WORLD"
@@ -43,10 +61,28 @@ describe("emitter", () => {
4361
emitter.dispose()
4462
})
4563

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
64+
it("should log an error if something goes wrong", async () => {
65+
const HELLO_WORLD = "HELLO_WORLD"
66+
const mockCallback = jest.fn(() => "Mock function called")
67+
const message = "You don't have access to that folder."
68+
69+
const emitter = new Emitter<{ event: string; callback: () => void }>()
70+
71+
const onHelloWorld = ({ event, callback }: { event: string; callback: () => void }): void => {
72+
if (event === HELLO_WORLD) {
73+
callback()
74+
throw new Error(message)
75+
}
76+
}
77+
78+
emitter.event(onHelloWorld)
79+
80+
await emitter.emit({ event: HELLO_WORLD, callback: mockCallback })
81+
82+
// Check that error was called
83+
expect(spy).toHaveBeenCalled()
84+
expect(spy).toHaveBeenCalledTimes(1)
85+
expect(spy).toHaveBeenCalledWith(message)
5086
})
5187
})
5288
})

0 commit comments

Comments
 (0)