How do I stub new Date() using sinon?

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

Leave a Comment