sandbox.useFakeTimers use cases

sandbox.useFakeTimers use cases

本文关键字:cases use useFakeTimers sandbox      更新时间:2023-09-26

sinon.useFakeTimers()可以存根全局日期构造函数new Date()

哪些目的和用例sandbox.useFakeTimers

从文档

伪造计时器并将时钟对象绑定到沙箱,以便在调用 sandbox.restore() 时也恢复它。通过沙盒时钟访问

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

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

这个想法不是要替换日期; 这是为了避免等待 setTimout,正如文档中所说的那样:

假计时器是 setTimeout 和朋友的同步实现 Sinon.JS可以覆盖全局函数,以允许您 更轻松地使用它们测试代码

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

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) 模拟时间流逝,然后断言测试正在通过。