/**
* DeterministicTestScheduler: A virtual time scheduler and test runner for deterministic testing of async systems.
*
* Features:
* - Virtual clock with `now()`, `tick(ms)`, `advance(ms)`, `runAll()`, etc.
* - Patches: Date.now(), performance.now(), setTimeout, setInterval, clearTimeout/clearInterval,
* setImmediate, process.nextTick (Node), queueMicrotask.
* - Separate queues for nextTick, microtasks (explicit), macrotasks/timers.
* - Deterministic execution: Timers run in FIFO order within same expiration time.
* - Test runner with auto-drain assertion to prevent leaks.
*
* Usage in tests:
* ```
* const scheduler = new DeterministicTestScheduler();
* scheduler.install();
*
* // Your code uses patched globals
* const p = new Promise(resolve => setTimeout(() => resolve('done'), 100));
*
* scheduler.clock.advance(50);
* // p not resolved yet
*
* scheduler.clock.tick(60); // now=110, runs the timer
*
* await p; // 'done'
*
* // Flush microtasks/timers explicitly as needed
* scheduler.drainMicrotasks();
* scheduler.clock.tick(0); // run 0-delay/immediates
*
* scheduler.assertDrained();
* scheduler.uninstall();
* ```
*
* For promises: Await them + `scheduler.clock.tick(0)` or `scheduler.drainPromises()` to flush microtasks before timers.
* Native Promises use real microtask queue; explicit queueMicrotask uses fake queue.
*
* Full test runner:
* ```
* await DeterministicTestRunner.run('my test', async (scheduler) => {
* // test code here
* });
* ```
*/
class DeterministicTestScheduler {
constructor() {
this.currentTime = 0;
this.nextTickQueue = [];
this.microQueue = [];
this.macros = new Map(); // id -> {fn: Function, args: any[], time: number, interval: number, repeat: boolean}
this.nextId = 1;
// Save originals
this.origDate = Date;
this.origDateNow = Date.now;
this.origPerformance = performance;
this.origPerformanceNow = performance?.now;
this.origSetTimeout = setTimeout;
this.origSetInterval = setInterval;
this.origClearTimeout = clearTimeout;
this.origClearInterval = clearInterval;
this.origSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : undefined;
this.origQueueMicrotask = queueMicrotask;
this.origProcessNextTick = typeof process !== 'undefined' ? process.nextTick : undefined;
this.Date = null;
this.performanceNow = null;
}
get clock() {
return {
now: () => this.currentTime,
tick: (ms) => {
this.currentTime += Math.max(0, ms);
this._runReadyMacros();
},
advance: (ms) => this.tick(ms),
next: () => {
const nextTask = this._getNextMacro();
if (nextTask) {
this.currentTime = Math.max(this.currentTime, nextTask.time);
this._runReadyMacros();
}
},
runAll: () => {
while (this.macros.size > 0) {
this.next();
}
},
reset: () => {
this.currentTime = 0;
this.macros.clear();
}
};
}
install() {
const self = this;
// Patch Date
function FakeDate(...args) {
if (args.length === 0) {
return new self.origDate(self.currentTime);
}
const d = new self.origDate(...args);
d.setTime(d.getTime() + (self.currentTime - self.origDateNow()));
return d;
}
FakeDate.prototype = self.origDate.prototype;
global.Date = FakeDate;
Date.now = () => self.currentTime;
// Patch performance.now
if (typeof performance !== 'undefined') {
performance.now = () => self.currentTime;
}
// Patch setTimeout
global.setTimeout = (fn, delay = 0, ...args) => {
const id = self.nextId++;
const actualDelay = Math.max(0, Number(delay) || 0);
self.macros.set(id, {
fn,
args,
time: self.currentTime + actualDelay,
interval: 0,
repeat: false
});
return id;
};
// Patch setInterval
global.setInterval = (fn, delay = 0, ...args) => {
const id = self.nextId++;
const actualDelay = Math.max(0, Number(delay) || 0);
self.macros.set(id, {
fn,
args,
time: self.currentTime + actualDelay,
interval: actualDelay,
repeat: true
});
return id;
};
// Patch clearTimeout / clearInterval
global.clearTimeout = global.clearInterval = (id) => {
self.macros.delete(id);
};
// Patch setImmediate
if (typeof setImmediate !== 'undefined') {
global.setImmediate = (fn, ...args) => {
return global.setTimeout(fn, 0, ...args);
};
}
// Patch queueMicrotask (explicit microtasks)
global.queueMicrotask = (task) => {
self.microQueue.push(task);
};
// Patch process.nextTick (Node)
if (typeof process !== 'undefined' && process.nextTick) {
process.nextTick = (fn, ...args) => {
self.nextTickQueue.push(() => fn(...args));
};
}
}
uninstall() {
// Restore globals
global.Date = this.origDate;
Date.now = this.origDateNow;
if (typeof performance !== 'undefined') {
performance.now = this.origPerformanceNow;
}
setTimeout = this.origSetTimeout;
setInterval = this.origSetInterval;
clearTimeout = this.origClearTimeout;
clearInterval = this.origClearInterval;
if (typeof setImmediate !== 'undefined') {
setImmediate = this.origSetImmediate;
}
queueMicrotask = this.origQueueMicrotask;
if (typeof process !== 'undefined' && this.origProcessNextTick) {
process.nextTick = this.origProcessNextTick;
}
}
_getNextMacro() {
let minTime = Infinity;
let nextId = Infinity;
let nextTask = null;
for (const [id, task] of this.macros) {
if (task.time < minTime || (task.time === minTime && id < nextId)) {
minTime = task.time;
nextId = id;
nextTask = task;
}
}
return nextTask;
}
_runReadyMacros() {
const ready = [];
for (const [id, task] of this.macros.entries()) {
if (task.time <= this.currentTime) {
ready.push({ id, task });
}
}
// Sort by time, then id (FIFO)
ready.sort((a, b) => a.task.time - b.task.time || a.id - b.id);
for (const { id, task } of ready) {
task.fn.apply(null, task.args);
if (task.repeat && task.interval > 0) {
task.time = this.currentTime + task.interval;
} else {
this.macros.delete(id);
}
}
}
runNextTicks() {
while (this.nextTickQueue.length > 0) {
const fn = this.nextTickQueue.shift();
fn();
}
}
runMicrotasks() {
while (this.microQueue.length > 0) {
const fn = this.microQueue.shift();
fn();
}
}
drainPromises() {
// Hack to drain native microtasks: queue fake immediate, await it (runs micros before)
// But since fake, combine with tick(0)
return new Promise((resolve) => {
const id = setImmediate(resolve);
this.clock.tick(0);
clearTimeout(id);
});
}
runFullCycle() {
this.runNextTicks();
this.runMicrotasks();
this._runReadyMacros();
}
assertDrained() {
const pending = {
nextTicks: this.nextTickQueue.length,
microtasks: this.microQueue.length,
macros: this.macros.size
};
if (Object.values(pending).some(n => n > 0)) {
throw new Error(`Pending tasks: ${JSON.stringify(pending)}`);
}
}
}
/**
* Test Runner
*/
class DeterministicTestRunner {
static async run(name, testFn) {
const scheduler = new DeterministicTestScheduler();
scheduler.install();
try {
await testFn(scheduler);
scheduler.assertDrained();
console.log(`✅ ${name}`);
} catch (error) {
console.error(`❌ ${name}: ${error.message}`);
throw error;
} finally {
scheduler.uninstall();
}
}
// Run multiple tests
static async runSuite(suiteName, tests) {
console.log(`🧪 Suite: ${suiteName}`);
for (const [name, testFn] of Object.entries(tests)) {
await this.run(name, testFn);
}
}
}
// Export for Node/CommonJS/ESM
if (typeof module !== 'undefined' && module.exports) {
module.exports = { DeterministicTestScheduler, DeterministicTestRunner };
} else {
globalThis.DeterministicTestScheduler = DeterministicTestScheduler;
globalThis.DeterministicTestRunner = DeterministicTestRunner;
}
// Example usage:
/*
async function exampleTest(scheduler) {
let value = 0;
const timerId = setTimeout(() => { value = 42; }, 100);
scheduler.clock.advance(99);
console.assert(value === 0, 'Not yet');
scheduler.clock.tick(1);
console.assert(value === 42, 'Set!');
clearTimeout(timerId);
}
DeterministicTestRunner.run('Example', exampleTest);
*/
This implementation provides a fully functional, deterministic test runner for async systems using virtual time. It emulates the JS event loop priorities (nextTick > microtask > macrotask/timer), advances time predictably, and ensures tests fail if tasks leak. Native Promise microtasks are handled via standard flush patterns combined with tick(0). For production-grade use, integrate with your test framework (e.g., wrap Jest/Vitest tests).