如何在javascript中伪造时间?

Leo*_*ang 37 javascript

我想模拟Date构造函数,这样每当我调用new Date()时,它总是返回特定的时间.

我发现Sinon.js提供useFakeTimers来模拟时间.但是以下代码对我不起作用.

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();
Run Code Online (Sandbox Code Playgroud)

tot*_*rio 51

sinon.useFakeTimers 接受时间戳(整数)作为参数,而不是Date对象.

试试吧

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)
Run Code Online (Sandbox Code Playgroud)

如果你使用类似的东西setTimeout,请确保你阅读文档,因为它useFakeTimers会破坏该代码的预期行为.

  • Sinon已经将其打破了[lolex](https://github.com/sinonjs/lolex). (7认同)

Mik*_*sen 28

这样的事怎么样?

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

var x = new Date();
document.write(x);
Run Code Online (Sandbox Code Playgroud)

当然,你可以运行:

Date = oldDate;

当您想要恢复正常行为时.

  • @tothemario为什么Sinon更喜欢这种方法? (3认同)
  • 在你的`afterEach`中不要忘记`Date = oldDate` (2认同)

Gil*_*tel 6

您还可以使用代理:

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);
    }
});
Run Code Online (Sandbox Code Playgroud)