Mocking JavaScript's current Date in Jest tests

Hugo Di Francesco - Jul 7 '18 - - Dev Community

There are situations where Date.now is used in application code. That code needs to be tested, and it’s always a struggle to remember how to mock Date.now. Here is the magic snippet:

const literallyJustDateNow = () => Date.now();

test('It should call and return Date.now()', () => {
  const realDateNow = Date.now.bind(global.Date);
  const dateNowStub = jest.fn(() => 1530518207007);
  global.Date.now = dateNowStub;

  expect(literallyJustDateNow()).toBe(1530518207007);
  expect(dateNowStub).toHaveBeenCalled();

  global.Date.now = realDateNow;
});
Enter fullscreen mode Exit fullscreen mode

This was sent out on the Code with Hugo newsletter last Monday.
Subscribe to get the latest posts right in your inbox (before anyone else).

This isn’t really a Jest-specific trick, we’re just accessing Node global object and replace Date.now with a stub.
We’re also being good unit-testing citizens and putting the original global.Date.now implementation back 😇.

Cover photo by Bryce Barker on Unsplash.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .