@@ -3,6 +3,9 @@ import { logger } from "@coder/logger"
3
3
import { Heart } from "../../../src/node/heart"
4
4
import { clean , mockLogger , tmpdir } from "../../utils/helpers"
5
5
6
+ function otherFake ( rejectMsg : string ) : ( ) => Promise < boolean > {
7
+ return ( ) => new Promise ( ( resolve , reject ) => setTimeout ( ( ) => reject ( Error ( rejectMsg ) ) , 100 ) )
8
+ }
6
9
describe ( "Heart" , ( ) => {
7
10
function isFakeActive ( resolveTo : boolean , rejectMessage ?: string ) : ( ) => Promise < boolean > {
8
11
return ( ) =>
@@ -28,6 +31,7 @@ describe("Heart", () => {
28
31
afterEach ( ( ) => {
29
32
jest . clearAllMocks ( )
30
33
jest . restoreAllMocks ( )
34
+ jest . useRealTimers ( )
31
35
} )
32
36
33
37
it ( "should write to a file when given a valid file path" , async ( ) => {
@@ -86,20 +90,30 @@ describe("Heart", () => {
86
90
maybe write a custom function and then try that and make sure
87
91
warn is called
88
92
93
+ problem is that that code will only run when
89
94
90
95
*/
91
- jest . spyOn ( global . Date , "now" ) . mockImplementationOnce ( ( ) => 60002 )
96
+ jest . useFakeTimers ( )
97
+ jest . setTimeout ( 6000 )
92
98
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
103
117
expect ( logger . warn ) . toBeCalled ( )
104
118
heart . dispose ( )
105
119
} )
0 commit comments