How do I stub new Date() using sinon?

sinon.useFakeTimers() was breaking some of my tests for some reason, I had to stub Date.now()

sinon.stub(Date, 'now').returns(now);

In that case in the code instead of const now = new Date(); you can do

const now = new Date(Date.now());

Or consider option of using moment library for date related stuff. Stubbing moment is easy.


I found this question when i was looking to solution how to mock Date constructor ONLY. I wanted to use same date on every test but to avoid mocking setTimeout. Sinon is using [lolex][1] internally Mine solution is to provide object as parameter to sinon:

let clock;

before(() => {
    clock = sinon.useFakeTimers({
        now: new Date(2019, 1, 1, 0, 0),
        shouldAdvanceTime: true,
        toFake: ["Date"],
    });
})

after(() => {
    clock.restore();
})

Other possible parameters you can find in [lolex][1] API [1]: https://github.com/sinonjs/lolex#api-reference


I suspect you want the useFakeTimers function:

var now = new Date();
var clock = sinon.useFakeTimers(now.getTime());
//assertions
clock.restore();

This is plain JS. A working TypeScript/JavaScript example:

var now = new Date();

beforeEach(() => {
    sandbox = sinon.sandbox.create();
    clock = sinon.useFakeTimers(now.getTime());
});

afterEach(() => {
    sandbox.restore();
    clock.restore();
});