forked from jamesshore/lets_code_javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_clock_test.js
More file actions
76 lines (63 loc) · 2.03 KB
/
_clock_test.js
File metadata and controls
76 lines (63 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright (c) 2017 Titanium I.T. LLC. All rights reserved. For license, see "README" or "LICENSE" file.
(function() {
"use strict";
const assert = require("_assert");
const Clock = require("./clock.js");
describe("Clock", function() {
let realClock;
let fakeClock;
beforeEach(function() {
realClock = new Clock();
fakeClock = Clock.createFake();
});
it("attaches to real system clock by default", function(done) {
const startTime = realClock.now();
setTimeout(() => {
try {
const elapsedTime = realClock.now() - startTime;
assert.gte(elapsedTime, 10);
done();
}
catch (err) { done(err); }
}, 10);
});
it("can use fake clock instead of real system clock", function() {
assert.equal(fakeClock.now(), 424242);
});
it("ticks the fake clock", function() {
const startTime = fakeClock.now();
fakeClock.tick(10000);
assert.equal(fakeClock.now(), startTime + 10000);
});
it("fails fast when attempting to tick system clock", function() {
assert.exception(() => realClock.tick());
});
it("tells us how many milliseconds have elapsed", function() {
const startTime = fakeClock.now();
fakeClock.tick(999);
assert.equal(fakeClock.millisecondsSince(startTime), 999);
});
it("fake clock runs a function every n milliseconds", function(done) {
const interval = fakeClock.setInterval(done, 10000);
fakeClock.tick(10000);
interval.clear();
fakeClock.tick(10000); // if clear() didn't work, done() will called twice and the test will fail
});
it("real clock runs a function every >=n milliseconds", function(done) {
let intervalCalled = false;
const startTime = realClock.now();
const interval = realClock.setInterval(() => {
try {
// If there's a GC cycle or other delay, this function may get called twice; prevent it
if (!intervalCalled) {
intervalCalled = true;
assert.gte(realClock.millisecondsSince(startTime), 10);
interval.clear();
done();
}
}
catch(err) { done(err); }
}, 10);
});
});
}());