File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ function countdown ( t , callback ) {
2+ console . log ( "Countdown started" )
3+ setTimeout ( function ( ) {
4+ console . log ( 'Countdown done!' ) ;
5+ callback ( ) ;
6+ } , t ) ;
7+ }
8+
9+ module . exports = {
10+ countdown : countdown
11+ }
Original file line number Diff line number Diff line change 1+ /* Based on Jest documentation: https://jestjs.io/docs/en/timer-mocks */
2+ 'use strict' ;
3+
4+ const { countdown } = require ( './clock' ) ;
5+ const fs = require ( "fs" ) ;
6+ const path = require ( "path" ) ;
7+ const fetch = require ( "node-fetch" ) ;
8+
9+ // Jest can fake the passage of time for javascript timers
10+ jest . useFakeTimers ( ) ;
11+
12+ /**
13+ * Countdown to be defined
14+ */
15+
16+ test ( 'Countdown function exists' , countdownExistsTest ) ;
17+
18+ function countdownExistsTest ( ) {
19+ expect ( countdown ) . toBeDefined ( ) ;
20+ }
21+
22+ /**
23+ * Countdown to delay execution of callback by 2000 millis
24+ */
25+
26+ test ( 'tests delay of countdown calls by 2 seconds' , countdownDelayTest ) ;
27+
28+ function countdownDelayTest ( ) {
29+ const t = 2000 ;
30+ const callback = jest . fn ( ) ;
31+
32+ countdown ( t , callback ) ;
33+
34+ // At this point in time, the callback should not have been called yet
35+ expect ( callback ) . not . toBeCalled ( ) ;
36+
37+ // Fast-forward until all timers have been executed
38+ jest . advanceTimersByTime ( t ) ;
39+
40+ // Now our callback should have been called!
41+ expect ( callback ) . toBeCalled ( ) ;
42+ expect ( callback ) . toHaveBeenCalledTimes ( 1 ) ;
43+
44+ }
You can’t perform that action at this time.
0 commit comments