Skip to content

Commit f10847c

Browse files
committed
Add timer example for jest testing
1 parent 95bf0ee commit f10847c

3 files changed

Lines changed: 55 additions & 5 deletions

File tree

clock.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
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+
}

clock.test.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
}

package-lock.json

Lines changed: 0 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)