The approach described here worked well for me, but then I stumbled onto another option that uses Jest's own API (I don't believe was available when this post was originally written). You can now do something like this:
import{jest}from'@jest/globals';// Tell Jest to use a different timer implementation. You can also// configure this in your jest.config.js file. For more info see// https://jestjs.io/docs/en/configuration#timers-string).jest.useFakeTimers('modern');jest.setSystemTime(newDate('04 Dec 1995 00:12:00 GMT').getTime());console.log(newDate());// "2014-01-09T00:00:00.000Z"// Back to reality...jest.useRealTimers();console.log(newDate());// prints the actual system time...
Thanks for sharing this--very helpful.
The approach described here worked well for me, but then I stumbled onto another option that uses Jest's own API (I don't believe was available when this post was originally written). You can now do something like this:
Thanks! That's true, it was added last may with Jest 26 :)
jestjs.io/blog/2020/05/05/jest-26
Thank you for this!
setSystemTime is giving error- setSystemTime does not exist on jest
Unfortunately
jest.useFakeTimers
seems to not work well with native Promises, which means you can't use it in anasync
call.github.com/facebook/jest/issues/10221