←back to thread

setBigTimeout

(evanhahn.com)
210 points cfj | 3 comments | | HN request time: 0s | source
Show context
bufferoverflow ◴[] No.41885979[source]
setTimeout is stranger than you think.

We recently had a failed unit test because setTimeout(fn, 1000) triggered at 999ms. That test had ran more than a hundred times before just fine. Till one day it didn't.

replies(5): >>41885984 #>>41886191 #>>41886471 #>>41886483 #>>41886563 #
1. steve_adams_86 ◴[] No.41886483[source]
Why does your unit test need to wait one second? Or are you controlling the system time, but it still had that error?
replies(1): >>41893165 #
2. bufferoverflow ◴[] No.41893165[source]
How else would you test if something happens after 1 second or not?
replies(1): >>41896686 #
3. steve_adams_86 ◴[] No.41896686[source]
By mocking the system time and manually progressing it a set amount of time. Otherwise your tests actually take seconds rather than a few milliseconds.

Not a great example, but here is something I did recently that tests time based state (thousands of seconds) but the suite passes in tens of milliseconds.

It also uses a random number generator with a deterministic mode to allow random behaviour in production, but deterministic results in tests (unrelated but also handy)

https://github.com/steveadams/minesweeper-store/blob/main/sr...

Some writing about the repo in case you’re curious: https://steve-adams.me/building-minesweeper-with-xstate-stor...