1

How to mock new Date() without arguments with jest?

I looked at the accepted answer on stackoverflow

  const mockDate = new Date(..);

    const spy = jest
        .spyOn(global, 'Date')
        .mockImplementation(() => mockDate)

What I expected is when jest runs the code: new Date() to use the mock. but when it run new Date(.....) to ignore the mock.

How to do it with jest? is it possible anyway?

slideshowp2
  • 63,310
  • 57
  • 191
  • 365
Jon Sud
  • 7,625
  • 10
  • 49
  • 105

1 Answers1

1

You can decide to use the original Date or the mock one inside mockImplementation.

E.g.

describe('70349270', () => {
  test('should pass', () => {
    const mockDate = new Date(1639533840728);
    const OriginlDate = global.Date;
    jest.spyOn(global, 'Date').mockImplementation((args) => {
      if (args) return new OriginlDate(args);
      return mockDate;
    });

    // test
    expect(new Date('1995-12-17T03:24:00').getTime()).toBeLessThan(1639533840728);
    expect(new Date().getTime()).toBe(1639533840728);
  });
});
slideshowp2
  • 63,310
  • 57
  • 191
  • 365