Emad Dehnavi
Emad Dehnavi

Reputation: 3441

Mock a date in jest not working in different environment

So I trying to Mock a date in my test, this is what I did :

const mockDate = new Date('2018-01-01');
const backupDate = Date;

beforeEach(() => {
  (global.Date as any) = jest.fn(() => mockDate);
})

afterEach(() => {
  (global.Date as any) = backupDate;
  jest.clearAllMocks();
});



const backupDate = Date;
(global.Date as any) = jest.fn(() => mockDate);
expect(myModule).toMatchSnapshot();
(global.Date as any) = jest.fn(() => backupDate);

So this test in my local works fine and it's match with my snapshots :

exports[`should match with date`] = `
[MockFunction] {
  "calls": Array [
    Array [
      Object {
           "myDate" : "Mon Jan 01 2018 01:00:00 GMT+0100 (Central European Standard Time)"
}]]}

but in production environment I getting this instead which cause failing the test : Mon Jan 01 2018 01:00:00 GMT+0100 (CET)

Any idea what is wrong?

Upvotes: 2

Views: 3107

Answers (1)

atool
atool

Reputation: 496

You should use jest.spyOn works for locking time:

let dateNowSpy;

beforeAll(() => {
    // Lock Time
    dateNowSpy = jest.spyOn(Date, 'now').mockImplementation(() => 1487076708000);
});

afterAll(() => {
    // Unlock Time
    dateNowSpy.mockRestore();
});

For Date & time test on Jest, I wrote a module named jest-date-mock which will make Date & Time test simply and controllable.

import { advanceBy, advanceTo, clear } from 'jest-date-mock';

test('usage', () => {
  advanceTo(new Date(2018, 5, 27, 0, 0, 0)); // reset to date time.

  const now = Date.now();

  advanceBy(3000); // advance time 3 seconds
  expect(+new Date() - now).toBe(3000);

  advanceBy(-1000); // advance time -1 second
  expect(+new Date() - now).toBe(2000);

  clear();
  Date.now(); // will got current timestamp
}); 

Upvotes: 7

Related Questions