javascript - sandbox.useFakeTimers 用例

标签 javascript unit-testing datetime sinon

sinon.useFakeTimers() 可以 stub 全局 Date 构造函数 new Date()

sandbox.useFakeTimers 具有哪些用途和用例?

来自文档

Fakes timers and binds the clock object to the sandbox such that it too is restored when calling sandbox.restore(). Access through sandbox.clock

目前还不清楚如何使用第二种方法。

SUT 中的new Date() 仍然返回原始时间戳

最佳答案

这个想法不是要取代 Date;而是要取代 Date。这是为了避免等待 setTimout,正如文档中所述:

Fake timers is a synchronous implementation of setTimeout and friends that Sinon.JS can overwrite the global functions with to allow you to more easily test code using them

以下是如何使用它的示例:

var assert = require('assert');
var sinon = require('sinon');

var executed = false;

function doSomething() {
    setInterval(function() {
        executed = true;
    }, 10000);
}

describe('doSomething', function() {

  beforeEach(function() {
    this.clock = sinon.useFakeTimers();
  });

  afterEach(function() {
    this.clock = sinon.restore();
  });

  it('should execute without waiting on the timeout', function(){
    doSomething();
    this.clock.tick(10001);
    assert.equal(executed, true);
  });

});

在此示例中,函数 doSomething 将在 10000 毫秒后执行。我们可以使用 this.clock.tick(10001) 来模拟时间的流逝,然后断言测试正在通过,而不是等待它来断言测试。

关于javascript - sandbox.useFakeTimers 用例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35774627/

相关文章:

java - jQuery 无法在 JSF(icefaces) 中工作

Javascript替换字符串中的动态文本

php - 在命名空间中组织 PHPUnit 测试

python - 模拟不适用于 pytest 和 flexmock

mysql - #1305 - 函数 [表名].ADD_DATE 不存在

javascript - 如何从 Javascript 检索 xml 数据

java - 用于查找数组中最大数量的参数化 Junit 测试用例的预期值

php - 如何将 GMT 时区传递给 PHP DateTime 对象?

csv - Logstash解析CSV日期

javascript - 分机JS : How to select a combobox item within item's root/index value?