如何在javascript中伪造时间? [英] How to fake time in javascript?

查看:136
本文介绍了如何在javascript中伪造时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to mock the Date constructor so that whenever I call new Date(), it always return specific time.

我发现Sinon.js提供了useFakeTimers模拟时间。但是下面的代码对我不起作用。

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


推荐答案

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

sinon.useFakeTimers accepts a timestamp (integer) as parameter, not a Date object.

尝试

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)

如果你使用类似的东西,请设置setTimeout ,请确保您阅读文档,因为 useFakeTimers 将破坏该代码的预期行为。

If you use anything like setTimeout, make sure you read the docs because the useFakeTimers will disrupt the expected behavior of that code.

这篇关于如何在javascript中伪造时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆