Mock current time with Moment.js or Day.js
The mock we actually need to set up in such a case is actually a partial one: we want it to act as a proxy for parameterized calls, passing them down to the original implementation, while returning a fixed value otherwise. Thankfully, Jest grants us the possibility to do so fairly easily:
jest.mock("dayjs", () => jest.fn((...args) => jest.requireActual("dayjs")(
args.filter(arg => arg).length > 0 ? ...args : "1989-03-21"
)));
As you can see, the aforementioned original implementation is available from within
jest.mock
's scope through the use of jest.requireActual
, allowing us to check if it was called with or without parameters, and pass a fixed value in the latter case.Congratulations, you are now able to freeze time!