How to fake time in javascript?

How about something like this?

var oldDate = Date;
Date = function (fake)
{
   return new oldDate('03/08/1980');
}

var x = new Date();
document.write(x);

You'd then, of course, run:

Date = oldDate;

When you wanted to restore things to normal behavior.


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.


You can also use Proxies:

window.Date = new Proxy(Date, {
    construct: function(target, args) {
        if (args.length === 0) {
            return new target(2017, 04, 13, 15, 03, 0);
        }
        return new target(...args);
    }
});

Tags:

Javascript