Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fake time in javascript?

Tags:

javascript

I would like to mock the Date constructor so that whenever I call new Date(), it always return specific time.

I found Sinon.js provide useFakeTimers to mock time. But the following code doesn't work for me.

sinon.useFakeTimers(new Date(2011,9,1));  //expect : 'Sat Oct 01 2011 00:00:00' ,  //result : 'Thu Oct 27 2011 10:59:44‘ var d = new Date(); 
like image 391
Leo Zhang Avatar asked Oct 28 '11 15:10

Leo Zhang


People also ask

How do you mock a Date in JavaScript?

You can use date-faker to mock what new Date() or Date. now() returns.

How do you mock a constructor like a new Date?

To mock a constructor like new Date() with Jest and JavaScript, we can use the setSystemTime method. beforeAll(() => { jest. useFakeTimers("modern"); jest. setSystemTime(new Date(2022, 3, 1)); }); afterAll(() => { jest.

How do you mock the current Date in jest?

import { advanceBy, advanceTo } 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).


1 Answers

sinon.useFakeTimers accepts a timestamp (integer) as parameter, not a Date object.

Try with

clock = sinon.useFakeTimers(new Date(2011,9,1).getTime()); new Date(); //=> return the fake Date 'Sat Oct 01 2011 00:00:00'  clock.restore(); new Date(); //=> will return the real time again (now) 

If you use anything like setTimeout, make sure you read the docs because the useFakeTimers will disrupt the expected behavior of that code.

like image 190
tothemario Avatar answered Oct 01 '22 11:10

tothemario