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();
You can use date-faker to mock what new Date() or Date. now() returns.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With