Skip to content

Commit 5024c67

Browse files
author
Joe Previte
committed
almost
1 parent 2b26a57 commit 5024c67

File tree

1 file changed

+25
-11
lines changed

1 file changed

+25
-11
lines changed

test/unit/node/heart.test.ts

+25-11
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ import { logger } from "@coder/logger"
33
import { Heart } from "../../../src/node/heart"
44
import { clean, mockLogger, tmpdir } from "../../utils/helpers"
55

6+
function otherFake(rejectMsg: string): () => Promise<boolean> {
7+
return () => new Promise((resolve, reject) => setTimeout(() => reject(Error(rejectMsg)), 100))
8+
}
69
describe("Heart", () => {
710
function isFakeActive(resolveTo: boolean, rejectMessage?: string): () => Promise<boolean> {
811
return () =>
@@ -28,6 +31,7 @@ describe("Heart", () => {
2831
afterEach(() => {
2932
jest.clearAllMocks()
3033
jest.restoreAllMocks()
34+
jest.useRealTimers()
3135
})
3236

3337
it("should write to a file when given a valid file path", async () => {
@@ -86,20 +90,30 @@ describe("Heart", () => {
8690
maybe write a custom function and then try that and make sure
8791
warn is called
8892
93+
problem is that that code will only run when
8994
9095
*/
91-
jest.spyOn(global.Date, "now").mockImplementationOnce(() => 60002)
96+
jest.useFakeTimers()
97+
jest.setTimeout(6000)
9298
const rejectMessage = "oh no"
93-
const heart = new Heart(`${testDir}/path.txt`, isFakeActive(false, rejectMessage))
94-
try {
95-
heart.beat()
96-
} catch (_e) {
97-
// nothing here
98-
}
99-
// HACK@jsjoeio - beat has some async logic but is not an async method
100-
// Therefore, we have to create an artificial wait in order to make sure
101-
// all async code has completed before asserting
102-
await new Promise((r) => setTimeout(r, 200))
99+
// Create Heart
100+
const heart = new Heart(`${testDir}/path.txt`, otherFake(rejectMessage))
101+
// Call beat
102+
heart.beat()
103+
// not alive so keep going
104+
expect(logger.trace).toBeCalled()
105+
// set last heart beat
106+
// skip logic because heartbeat timer undefined
107+
// set timeout which sets a function that gets called after 60 seconds
108+
// so we should advance timers by 60 seconds
109+
// then it should get called and isActive should be false or it should reject
110+
jest.advanceTimersToNextTimer()
111+
// await new Promise((r) => setTimeout(r, 200))
112+
113+
// write file which takes a sec
114+
// HACK@jsjoeio - beat has some async logic but is not an async method
115+
// Therefore, we have to create an artificial wait in order to make sure
116+
// all async code has completed before asserting
103117
expect(logger.warn).toBeCalled()
104118
heart.dispose()
105119
})

0 commit comments

Comments
 (0)