Fake setTimeout, clearTimeout, and Date.now for controllable time
Create a FakeTimer class that can be used to replace the native JavaScript timing functions (setTimeout, clearTimeout, and Date.now) with a controllable fake version. This allows for the simulation and testing of time-dependent code without the need for actual time to elapse, making it ideal for tests and simulations where precise timing control is required. A fake timer in JavaScript replaces setTimeout() and friends, much like Jest’s fake timers.
The FakeTimer class should provide the following functionalities:
Usage Example:
const timer = new FakeTimer();
timer.install();
// Schedule a timeout
const id = setTimeout(() => console.log('Timeout called'), 100);
// Advance the fake timer
timer.tick();
// 'Timeout called' is logged to the console
timer.uninstall(); // Restore original functions
This feature is particularly useful in unit testing, where real-time waiting is impractical. It allows for precise control over the execution timing of callbacks, enabling more deterministic and faster tests.