/**
* A deterministic test runner for async code using virtual time.
*
* Features:
* - Fake timers (setTimeout, setInterval, clearTimeout, clearInterval).
* - Fake queueMicrotask (for Promises and async/await).
* - Virtual clock advancement: tick(ms), advanceTime(ms), runAll(), runToNextTask().
* - Per-test isolation with global patches restored after each test.
* - Supports async test functions; pass the clock to control time progression.
* - Deterministic: no real time passes, tests run in fixed order and timing.
*
* Usage:
*
* const runner = new VirtualTimeTestRunner();
*
* runner.test('basic timeout', async (clock) => {
* let called = 0;
* const id = setTimeout(() => { called++; }, 100);
* clock.tick(100);
* clearTimeout(id);
* clock.tick(100); // won't fire
* expect(called).toBe(1);
* });
*
* runner.test('promise + timeout', async (clock) => {
* const p = new Promise(resolve => setTimeout(resolve, 50));
* clock.tick(50);
* await p; // resolves deterministically
* });
*
* runner.test('interval', async (clock) => {
* let count = 0;
* const id = setInterval(() => { count++; if (count === 3) clearInterval(id); }, 10);
* clock.tick(35);
* expect(count).toBe(3);
* });
*
* // Run all tests
* await runner.run();
*
* Notes:
* - Tests receive the `clock` as argument to manually advance time.
* - Always advance time *before* awaiting timer-dependent promises.
* - `runAll()` advances time and runs all pending tasks until idle.
* - Errors in tests are caught and reported.
* - Assumes Node.js (uses `global`). For browser, adapt `global` to `window`.
*/
class VirtualClock {
constructor() {
this.currentTime = 0;
this.nextTimerId = 1;
this.timers = new Map();
this.macrotasks = [];
this.microtasks = [];
}
queueMicrotask(callback) {
this.microtasks.push(callback);
}
_runMicrotasks() {
while (this.microtasks.length > 0) {
const callback = this.microtasks.shift();
try {
callback();
} catch (error) {
console.error('Microtask error:', error);
}
}
}
setTimeout(callback, delay = 0) {
const id = this.nextTimerId++;
const scheduledTime = this.currentTime + Math.max(0, delay);
const timer = {
id,
fn: callback,
scheduledTime,
interval: 0,
};
this.timers.set(id, timer);
this.macrotasks.push(timer);
this.macrotasks.sort((a, b) => a.scheduledTime - b.scheduledTime);
return id;
}
setInterval(callback, interval) {
const id = this.nextTimerId++;
const scheduledTime = this.currentTime + Math.max(0, interval);
const timer = {
id,
fn: callback,
scheduledTime,
interval: interval || 0,
};
this.timers.set(id, timer);
this.macrotasks.push(timer);
this.macrotasks.sort((a, b) => a.scheduledTime - b.scheduledTime);
return id;
}
clearTimeout(id) {
this.timers.delete(id);
}
clearInterval(id) {
this.clearTimeout(id);
}
_runNextMacrotask() {
while (this.macrotasks.length > 0) {
const timer = this.macrotasks[0];
if (timer.scheduledTime > this.currentTime) {
return;
}
this.macrotasks.shift();
if (!this.timers.has(timer.id)) {
continue; // cleared
}
try {
timer.fn();
} catch (error) {
console.error('Macrotask error:', error);
}
if (timer.interval > 0) {
timer.scheduledTime = this.currentTime + timer.interval;
this.macrotasks.push(timer);
this.macrotasks.sort((a, b) => a.scheduledTime - b.scheduledTime);
}
return;
}
}
tick(ms) {
this.advanceTime(ms);
}
advanceTime(ms) {
this.currentTime += Math.max(0, ms);
this._pump();
}
_pump() {
// Run microtasks first
this._runMicrotasks();
// Run all due macrotasks
while (this.macrotasks.length > 0 && this.macrotasks[0].scheduledTime <= this.currentTime) {
this._runNextMacrotask();
this._runMicrotasks();
}
}
runToNextTask() {
this._runMicrotasks();
if (this.macrotasks.length === 0) return;
const nextScheduled = this.macrotasks[0].scheduledTime;
this.currentTime = Math.max(this.currentTime, nextScheduled);
this._runNextMacrotask();
this._runMicrotasks();
}
runAll() {
this._runMicrotasks();
while (this.macrotasks.length > 0) {
const nextScheduled = this.macrotasks[0].scheduledTime;
this.currentTime = Math.max(this.currentTime, nextScheduled);
this._runNextMacrotask();
this._runMicrotasks();
}
}
now() {
return this.currentTime;
}
reset() {
this.currentTime = 0;
this.nextTimerId = 1;
this.timers.clear();
this.macrotasks.length = 0;
this.microtasks.length = 0;
}
}
class VirtualTimeTestRunner {
constructor() {
this.tests = [];
this.results = [];
}
test(name, testFn) {
this.tests.push({ name, testFn });
}
async run() {
for (const { name, testFn } of this.tests) {
const result = { name, status: 'pending' };
this.results.push(result);
const clock = new VirtualClock();
// Save originals
const originals = {
setTimeout: global.setTimeout,
setInterval: global.setInterval,
clearTimeout: global.clearTimeout,
clearInterval: global.clearInterval,
queueMicrotask: global.queueMicrotask,
};
// Patch globals
global.setTimeout = clock.setTimeout.bind(clock);
global.setInterval = clock.setInterval.bind(clock);
global.clearTimeout = clock.clearTimeout.bind(clock);
global.clearInterval = clock.clearInterval.bind(clock);
global.queueMicrotask = clock.queueMicrotask.bind(clock);
try {
await testFn(clock);
clock.runAll();
result.status = 'pass';
} catch (error) {
result.status = 'fail';
result.error = error.message;
} finally {
// Restore originals
global.setTimeout = originals.setTimeout;
global.setInterval = originals.setInterval;
global.clearTimeout = originals.clearTimeout;
global.clearInterval = originals.clearInterval;
global.queueMicrotask = originals.queueMicrotask;
}
// Log result
console.log(`${result.status.toUpperCase()}: ${name}`);
if (result.error) {
console.error(result.error);
}
}
const passes = this.results.filter(r => r.status === 'pass').length;
const total = this.results.length;
console.log(`\nSummary: ${passes}/${total} tests passed.`);
return this.results;
}
}
module.exports = { VirtualTimeTestRunner, VirtualClock };
// For ESM/ direct use:
// export { VirtualTimeTestRunner, VirtualClock };
This is a complete, standalone, deterministic test runner. It patches globals per test for isolation, supports async tests via the injected clock, and automatically runs all pending tasks after the test function completes. Tests are deterministic because time only advances explicitly or via runAll(). Add your own assertions (e.g., expect, assert) inside test functions. Run await runner.run() to execute all registered tests and get results.