DEV Community

Cover image for [Stop Fighting the Clock] - How to Control Time in Your Tests Without Hacks
beladevo
beladevo

Posted on

[Stop Fighting the Clock] - How to Control Time in Your Tests Without Hacks

Hey everyone ๐Ÿ‘‹

I wanted to share a little library Iโ€™ve been building lately, called timewarp-sim. If youโ€™ve ever had to test date logic or simulate time passing, you know how frustrating it can be. You either end up waiting forever, fiddling with your system clock, or writing tons of brittle mocks.

timewarp-sim solves this cleanly by giving you a deterministic time machine for your JavaScript and TypeScript code.


โœจ What does it do?

โœ… Freeze time at a specific moment
โœ… Advance time however you like (seconds, hours, even decades)
โœ… Travel to any timestamp instantly
โœ… Globally mock Date.now() and new Date() so all your dependencies see the same simulated clock
โœ… Register hooks to react whenever time changes
โœ… Unfreeze and return to real time anytime


๐Ÿ’ก Why should you care?

If you work on:

  • Session or token expiration logic
  • Caching and TTL validation
  • Recurring jobs (cron-like scheduling)
  • Billing or subscription renewals
  • Reports that aggregate data by date
  • Anything else where time matters

โ€ฆthis tool can save you hours of debugging and testing.

You no longer have to wait for timeouts to expire or write fragile setTimeout hacks- just jump forward in time with a single line of code.


โšก Quick Example

import { Timewarp } from "timewarp-sim";

console.log("Real time:", new Date());

Timewarp.freeze();
console.log("Frozen:", Timewarp.now());

Timewarp.enableGlobalMocking();
console.log("Mocked Date.now():", Date.now());

Timewarp.advance(60 * 60 * 1000);
console.log("After 1 hour:", new Date());

Timewarp.travelTo(new Date("2040-01-01T00:00:00Z"));
console.log("Traveled to:", new Date());

Timewarp.unfreeze();
Timewarp.disableGlobalMocking();
console.log("Back to real time:", new Date());
Enter fullscreen mode Exit fullscreen mode

๐ŸŒŸ Get Involved

timewarp-sim is open source, and Iโ€™d love to see it grow with help from the community!

๐Ÿ‘‰ โญ Star the project on GitHub
๐Ÿ‘‰ Open issues for bugs or feature ideas
๐Ÿ‘‰ Contribute code if you want to make it even better

If you find it useful, share it with your teammates or that friend who still uses setTimeout(999999999) to simulate waiting.

Top comments (1)

Collapse
 
beladevo profile image
beladevo • Edited