time-fast-forward
Version:
Fake the system time (Date, hrtime) in your tests, without freezing it (unlike in many other libraries). Freeze only when you need.
74 lines (73 loc) • 2.53 kB
JavaScript
;
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FakeDate = exports.getCurrentTimeShift = exports.setTimeShift = exports.restoreDate = exports.fakeDate = void 0;
const OriginalDate = Date;
const originalProcessHrTime = process === null || process === void 0 ? void 0 : process.hrtime;
const originalProcessHrTimeBigInt = (_a = process === null || process === void 0 ? void 0 : process.hrtime) === null || _a === void 0 ? void 0 : _a.bigint;
let globalTimeShift = 0;
exports.fakeDate = () => {
if (FakeDate === Date) {
return;
}
if (typeof window !== 'undefined') {
window.Date = FakeDate;
}
else {
global.Date = FakeDate;
process.hrtime = patchedProcessHrTime;
}
};
exports.restoreDate = () => {
if (typeof window !== 'undefined') {
if (OriginalDate === window.Date) {
return;
}
window.Date = OriginalDate;
}
else {
if (OriginalDate === global.Date) {
return;
}
global.Date = OriginalDate;
process.hrtime = originalProcessHrTime;
}
globalTimeShift = 0;
};
function patchedProcessHrTime(...args) {
const result = originalProcessHrTime.call(process, ...args);
result[0] += Math.floor(globalTimeShift / 1000);
result[1] += (globalTimeShift % 1000) * 1000000; // ms -> ns
if (result[1] >= 1000000000) {
// if nanoseconds > 1s
result[0] += 1;
result[1] %= 1000000000;
}
return result;
}
patchedProcessHrTime.bigint = function () {
const result = originalProcessHrTimeBigInt.call(process);
return (result +
(BigInt(Math.round(globalTimeShift)) *
BigInt(1000000)) // ms -> ns
);
};
exports.setTimeShift = (shift) => (globalTimeShift = shift);
exports.getCurrentTimeShift = () => globalTimeShift;
class FakeDate extends Date {
static now() {
return OriginalDate.now() + globalTimeShift;
}
constructor(y, m, d, h, M, s, ms) {
super();
switch (arguments.length) {
case 0:
return new OriginalDate(OriginalDate.now() + globalTimeShift);
case 1:
return new OriginalDate(y);
default:
return new OriginalDate(y, m, d !== null && d !== void 0 ? d : 1, h !== null && h !== void 0 ? h : 0, M !== null && M !== void 0 ? M : 0, s !== null && s !== void 0 ? s : 0, ms !== null && ms !== void 0 ? ms : 0);
}
}
}
exports.FakeDate = FakeDate;