2017-04-20 19:17:05 -04:00
|
|
|
const test = require('tap').test;
|
|
|
|
const Timer = require('../../src/util/timer');
|
2016-04-18 17:20:30 -04:00
|
|
|
|
2019-03-26 11:56:50 -04:00
|
|
|
// Stubbed current time
|
|
|
|
let NOW = 0;
|
|
|
|
|
|
|
|
const testNow = {
|
|
|
|
now: () => {
|
|
|
|
NOW += 100;
|
|
|
|
return NOW;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2017-04-20 19:17:05 -04:00
|
|
|
test('spec', t => {
|
2019-03-26 11:56:50 -04:00
|
|
|
const timer = new Timer(testNow);
|
2016-04-18 17:20:30 -04:00
|
|
|
|
|
|
|
t.type(Timer, 'function');
|
|
|
|
t.type(timer, 'object');
|
|
|
|
|
|
|
|
t.type(timer.startTime, 'number');
|
|
|
|
t.type(timer.time, 'function');
|
|
|
|
t.type(timer.start, 'function');
|
2016-04-26 17:03:22 -04:00
|
|
|
t.type(timer.timeElapsed, 'function');
|
2019-02-11 15:14:44 -05:00
|
|
|
t.type(timer.setTimeout, 'function');
|
|
|
|
t.type(timer.clearTimeout, 'function');
|
2016-04-18 17:20:30 -04:00
|
|
|
|
|
|
|
t.end();
|
|
|
|
});
|
|
|
|
|
2017-04-20 19:17:05 -04:00
|
|
|
test('time', t => {
|
2019-03-26 11:56:50 -04:00
|
|
|
const timer = new Timer(testNow);
|
2017-04-20 19:17:05 -04:00
|
|
|
const time = timer.time();
|
2016-04-18 17:20:30 -04:00
|
|
|
|
2019-03-26 11:56:50 -04:00
|
|
|
t.ok(testNow.now() >= time);
|
2016-04-18 17:20:30 -04:00
|
|
|
t.end();
|
|
|
|
});
|
|
|
|
|
2017-04-20 19:17:05 -04:00
|
|
|
test('start / timeElapsed', t => {
|
2019-03-26 11:56:50 -04:00
|
|
|
const timer = new Timer(testNow);
|
2017-04-20 19:17:05 -04:00
|
|
|
const delay = 100;
|
2017-08-26 13:07:47 -04:00
|
|
|
const threshold = 1000 / 60; // 60 hz
|
2016-04-18 17:20:30 -04:00
|
|
|
|
|
|
|
// Start timer
|
|
|
|
timer.start();
|
|
|
|
|
2019-03-26 11:56:50 -04:00
|
|
|
// Measure timer
|
|
|
|
const timeElapsed = timer.timeElapsed();
|
|
|
|
t.ok(timeElapsed >= 0);
|
|
|
|
t.ok(timeElapsed >= (delay - threshold) &&
|
|
|
|
timeElapsed <= (delay + threshold));
|
|
|
|
t.end();
|
2016-04-18 17:20:30 -04:00
|
|
|
});
|
2019-02-11 15:14:44 -05:00
|
|
|
|
|
|
|
test('setTimeout / clearTimeout', t => new Promise((resolve, reject) => {
|
2019-03-26 11:56:50 -04:00
|
|
|
const timer = new Timer(testNow);
|
2019-02-11 15:14:44 -05:00
|
|
|
const cancelId = timer.setTimeout(() => {
|
|
|
|
reject(new Error('Canceled task ran'));
|
|
|
|
}, 1);
|
|
|
|
timer.setTimeout(() => {
|
|
|
|
resolve('Non-canceled task ran');
|
|
|
|
t.end();
|
|
|
|
}, 2);
|
|
|
|
timer.clearTimeout(cancelId);
|
|
|
|
}));
|