DEV Community

Cover image for I got tired of mocking Date, so I built a TimeProvider for TypeScript
jaenyf
jaenyf

Posted on

I got tired of mocking Date, so I built a TimeProvider for TypeScript

Every (or at least a lot of) project seems to have code like this somewhere:

if (user.subscriptionEndsAt < new Date()) {
// ...
}

There's nothing wrong with it... until you have to test it.

Then you end up freezing time, mocking Date, enabling fake timers, remembering to restore them afterwards, and hoping another test didn't leave the clock in a weird state.

While Jest's and Vitest's fake timers are great tools, they always felt like they were solving the problem from the outside by patching global APIs.

I wanted to try something different.

Time is a dependency

When you think about it, the current time isn't much different from a database or an HTTP client.

Your business logic depends on it, but it doesn't have to know where it comes from.

Instead of writing this:

const now = new Date();

what if we wrote this?

const now = timeProvider.now();

Suddenly, testing becomes boring—in the best possible way.

You don't need global fake timers anymore. You just pass a different implementation.

.NET had the same idea

While looking into this, I discovered that .NET 8 introduced a TimeProvider abstraction.

Seeing that was reassuring. It suggested I wasn't the only one who felt that "current time" deserved to be treated as a real dependency.

I didn't want to copy the .NET API, but I did like the underlying idea.

So I started building a version that felt natural in the TypeScript ecosystem.

It grew beyond a clock

At first I only wanted to replace new Date().

Then I realized the same issue exists with setTimeout, setInterval, performance measurements, and a few other APIs.

They all depend on the environment's notion of time.

So the library slowly became an abstraction around all of those instead of just "what time is it?".

Is this actually useful?

That's the part I'm still curious about.

In the projects I've worked on, I prefer injecting time over patching globals during tests.

Maybe other teams have reached the same conclusion.

Maybe everyone is perfectly happy with fake timers and I'm overengineering things.

Either way, I'd love to hear how other TypeScript developers approach this.

If you're interested, the project is here:

https://jaenyf.github.io/time-provider/

Feedback, criticism, and alternative approaches are all welcome.

Top comments (0)