Jon Sud
Jon Sud

Reputation: 11641

How to mock new date only when it's have no arguments?

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?

Upvotes: 2

Views: 3202

Answers (1)

Lin Du
Lin Du

Reputation: 102257

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);
  });
});

Upvotes: 1

Related Questions