sandbox.useFakeTimers用例

时间:2016-03-03 14:16:40

标签: javascript unit-testing datetime sinon

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

哪些用途和用例有sandbox.useFakeTimers

来自文档

  

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

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

new Date()中的

SUT仍会返回原始时间戳

1 个答案:

答案 0 :(得分:0)

这个想法不是取代日期;这是为了避免像在文档中所说的那样等待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)来模拟测试通过时,而不是等待它来断言测试,然后断言测试正在通过。

相关问题