DEV Community

Cover image for Mocking JavaScript's current Date in Jest tests
Hugo Di Francesco
Hugo Di Francesco

Posted on • Originally published at on

Mocking JavaScript's current Date in Jest tests

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

const literallyJustDateNow = () =>;

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

  expect(dateNowStub).toHaveBeenCalled(); = 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 with a stub.
We’re also being good unit-testing citizens and putting the original implementation back 😇.

Cover photo by Bryce Barker on Unsplash.

Top comments (5)

joelnet profile image
JavaScript Joel

You might run the risk of tests after this one failing if there is an exception in this test that prevents being set back.

Using beforeEach and after each could help with Code reuse and this possible scenario.

patroza profile image
Patrick Roza

Wrap in try, finally. Alternatively create a utility function to create now date, and mock that

pies profile image
Michał T.

Also great for mocking Math.random I imagine.

borys_kupar profile image
Borys Kupar

How can you mock date constructor?
So imagine date is created with "const now = new Date()".
I would like to have "now" to have specific mocked date.

hugo__df profile image
Hugo Di Francesco

global.Date = myMockConstructor