Skip to content

Commit 2d39822

Browse files
committed
test: use sinon mock timers for determinstic timer testing
Using sinon's ability to mock the system clock, we can make testing the interruptable async timer more deterministc across platforms. NODE-2684
1 parent 2cb895e commit 2d39822

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

test/unit/utils.test.js

+20-10
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const eachAsync = require('../../lib/core/utils').eachAsync;
33
const makeInterruptableAsyncInterval = require('../../lib/utils').makeInterruptableAsyncInterval;
44
const now = require('../../lib/utils').now;
55
const expect = require('chai').expect;
6+
const sinon = require('sinon');
67

78
describe('utils', function() {
89
context('eachAsync', function() {
@@ -37,7 +38,13 @@ describe('utils', function() {
3738
});
3839

3940
context('makeInterruptableAsyncInterval', function() {
40-
const roundToNearestMultipleOfTen = x => Math.round(x / 10) * 10;
41+
before(function() {
42+
this.clock = sinon.useFakeTimers();
43+
});
44+
45+
after(function() {
46+
this.clock.restore();
47+
});
4148

4249
it('should execute a method in an repeating interval', function(done) {
4350
let lastTime = now();
@@ -52,11 +59,13 @@ describe('utils', function() {
5259
);
5360

5461
setTimeout(() => {
55-
const roundedMarks = marks.map(roundToNearestMultipleOfTen);
56-
expect(roundedMarks.every(mark => roundedMarks[0] === mark)).to.be.true;
62+
expect(marks).to.eql([10, 10, 10, 10, 10]);
63+
expect(marks.every(mark => marks[0] === mark)).to.be.true;
5764
executor.stop();
5865
done();
59-
}, 50);
66+
}, 51);
67+
68+
this.clock.tick(51);
6069
});
6170

6271
it('should schedule execution sooner if requested within min interval threshold', function(done) {
@@ -75,11 +84,12 @@ describe('utils', function() {
7584
executor.wake();
7685

7786
setTimeout(() => {
78-
const roundedMarks = marks.map(roundToNearestMultipleOfTen);
79-
expect(roundedMarks[0]).to.be.lessThan(50);
87+
expect(marks).to.eql([10, 50]);
8088
executor.stop();
8189
done();
82-
}, 50);
90+
}, 100);
91+
92+
this.clock.tick(100);
8393
});
8494

8595
it('should debounce multiple requests to wake the interval sooner', function(done) {
@@ -99,12 +109,12 @@ describe('utils', function() {
99109
}
100110

101111
setTimeout(() => {
102-
const roundedMarks = marks.map(roundToNearestMultipleOfTen);
103-
expect(roundedMarks[0]).to.be.lessThan(50);
104-
expect(roundedMarks.slice(1).every(mark => mark === 50)).to.be.true;
112+
expect(marks).to.eql([10, 50, 50, 50, 50]);
105113
executor.stop();
106114
done();
107115
}, 250);
116+
117+
this.clock.tick(250);
108118
});
109119
});
110120
});

0 commit comments

Comments
 (0)