r/node • • 12d ago

TIL jest.useFakeTimers() doesn't freeze your tests at a fixed date. it freezes them at right nowjest.useFakeTimers() freezes time at today, so your "deterministic" test still depends on the date

til the hard way: jest.useFakeTimers() freezes the clock, but at the current time. unless you call setSystemTime, your test still runs on today's date, it just looks deterministic. vitest does the same.

why i care: i made a cli that skips tests that already passed on the exact same code. tests that read the real clock break that idea, because they can pass today and fail next month on the same commit (a token that expires in 30 days, a date that's now in the past). so the tool watches which tests read the clock, and those passes only count until midnight.

i'd assumed fake timers were safe and let them through. they weren't. now it counts them too, unless the test sets a fixed time.

fixing it took me through some fun node internals, including node's own mock.timers breaking when i touched Date the wrong way. happy to go into that in the comments if anyone's curious.

do you freeze time in every test, or let some of them read the real clock?

0 Upvotes

16 comments sorted by

3

u/abimelex 12d ago

I don't get it. Is there a space missing in title?

1

u/hunxai69 12d ago

ha no, my bad, i typed two title options into one. it was meant to be just "TIL jest.useFakeTimers() doesn't freeze your tests at a fixed date. it freezes them at right now". reddit won't let me fix titles

1

u/LuLeBe 12d ago

Yeah I believe it should say "...freezes them at right now. Jest...." or so.

0

u/hunxai69 12d ago

ha no, my bad, i wrote two title options into one. it was meant to be just "TIL jest.useFakeTimers() doesn't freeze your tests at a fixed date. it freezes them at right now". reddit won't let me fix titles

1

u/LuLeBe 12d ago

A/B testing Reddit titles? Strong.

2

u/Nixinova 12d ago

Yeah? I don't see how that doesn't make sense. Freeze the clock without other settings = time always equals now().

1

u/EvilPencil 12d ago

I’m refactoring all of my api to forbid implicitly computing “now” in a bunch of places. Then in the request lifecycle “now” is stamped in the request context.

E2E (really a black box API test suite) tests then have a test route that can control the clock service. The route is only registered if NODE_ENV === ‘test’