(jest-fake-timers): Add now() API to get the fake clock time - #13244
Merged
Conversation
Member
|
CI is my bad - will fix as soon as I'm home from birthday gift shopping |
mrazauskas
reviewed
Sep 10, 2022
SimenB
reviewed
Sep 10, 2022
|
|
||
| ### `jest.now()` | ||
|
|
||
| Returns the time in ms of the current fake clock. |
Member
There was a problem hiding this comment.
Add a note this is equivalent to Date.now() for non-legacy timers?
Contributor
Author
There was a problem hiding this comment.
Summary
Currently, users of legacy fake timers have no way to mock other time-related APIs in a way that keeps a consistent clock with the Jest mocked APIs.
Exposing the fake time allows easy mocking of APIs like
Date.now(),performance.now(), etc.Use case
For example, React Native's
TimingAnimationuses a combination of time elapsed according toDate.now()to interpolate state within each update, andrequestAnimationFrame()to set a timer for the next update.The legacy timers API in Jest 27+ mocks
requestAnimationFrame(taking ~16ms of fake clock time per frame), butDate.now()is not mocked, which means thatadvanceTimersToTimeruns some number of animation frames, but doesn't advanceDate.now()time by the corresponding amount.jest.runAllTimers()"works", but only because it actually ends up running for the real time of the animation, processing as many frames as the CPU allows.What would be useful is a way to mock APIs like
Date.now()orperformance.now()in a manner consistent with the internal fake clock, but Jest doesn't expose the internal clock, so we're left guessing about whatDate.now()should return after an unknown number of timers/frames have run.(
requestAnimationFramedoes actually pass the current high-res clock time to its callback, but for "reasons"(?)TimingAnimationdoesn't use it - in any case that doesn't really help a test author, and we'd still need to mock a start time.)Before
About the best we can do at the moment is to advance frame by frame:
(Alternatives include a mock implementation of
Date.now()that "knows about" the number of frames processed, eg by assuming it's called once per frame, which is also not great!)After
Test Plan
I've added tests for modern and legacy timers, and also tested the "After" above with React Native animation.