SirrMaxi
SirrMaxi

Reputation: 643

Jest can't advance timers related to Date

I'm trying to advance in time. I tried making this simple test:

it.only('Advance in time', async() => {
  console.log('primer clg', new Date(Date.now()).toISOString())
  jest.advanceTimersByTime(1000)
  console.log('segundo clg', new Date(Date.now()).toISOString())
})

But const pepe is always the same time... what I'm doing wrong? How can I advance in time?

console.log
    2022-04-06T19:08:12.795Z

console.log
    2022-04-06T19:08:12.795Z

Upvotes: 2

Views: 1642

Answers (1)

Lin Du
Lin Du

Reputation: 102597

From the doc Advance Timers by Time:

jest.advanceTimersByTime(msToRun). When this API is called, all timers are advanced by msToRun milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed during this time frame, will be executed.

This API is not used to fast forward Date. It's used for advanced the timers set by setTimeout() or setInterval()

For Date testing, you probably need to mock date, so that your test code does not depend on system time. Then you can run your test code in any CI/CD servers which have different OS and timezones.

You can call jest.fn().mockReturnValueOnce multiple times to mock different return values.

mockDate1 is the return value of the first call to Date.now(), mockDate2 is the return value of the second call to Date.now(). Both of them have fixed timestamps.

describe('first', () => {
  it('Advance in time', async () => {
    const mockDate1 = new Date(1649272092795);
    const mockDate2 = new Date(1649272092795 + 1_000);
    jest.spyOn(global.Date, 'now').mockReturnValueOnce(mockDate1).mockReturnValueOnce(mockDate2);
    console.log('primer clg', new Date(Date.now()).toISOString()); 
    console.log('segundo clg', new Date(Date.now()).toISOString());
  });
});

Test result:

 PASS  stackoverflow/71772373/index.test.js
  first
    ✓ Advance in time (14 ms)

  console.log
    primer clg 2022-04-06T19:08:12.795Z

      at Object.<anonymous> (stackoverflow/71772373/index.test.js:6:13)

  console.log
    segundo clg 2022-04-06T19:08:13.795Z

      at Object.<anonymous> (stackoverflow/71772373/index.test.js:7:13)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.867 s, estimated 1 s

Upvotes: 5

Related Questions