【问题标题】:How to test set Interval in sinon js如何在 sinon js 中测试集合间隔
【发布时间】:2016-04-28 05:12:04
【问题描述】:

我正在尝试为setInterval() 编写单元测试,但我不确定如何监视fetchState()

maincode.js:

var pollStatus = function(interval, killPolling) {
   // Clear Interval if function is called again 
   if (killPolling || StatusPollObj) {
        clearInterval(StatusPollObj);
        StatusPollObj = false;
    }

    // Call once before setInterval Starts
    fetchState();
    StatusPollObj = setInterval(function() {
        if(somecondtion_to_check_inactivity) return;
        fetchState();
    }, interval);
};

spec.js

 it("state.json setInterval Call",function() {
    this.clock = sinon.useFakeTimers();
    var helper = new state.HELPER();
    var spy = sinon.spy(helper, "fetchState");

    helper.pollStatus('80000', false);
    expect(spy.called).to.be.true;
    this.clock.tick(80000);
    expect(spy.called).to.be.true;
});

【问题讨论】:

    标签: javascript mocha.js sinon sinon-chai


    【解决方案1】:

    间谍未注册到 setInterval。您的函数 fetchState 应作为参数传递给函数。

    var someFun = function(callFunc, interval, killPolling) {
        callFunc();
        StatusPollObj = setInterval(function() {
            if(somecondtion_to_check_inactivity) return;
            callFunc();
        }, interval);
    } 
    

    你的测试应该是这样的

    it("state.json setInterval Call",function() {
        this.clock = sinon.useFakeTimers();
        var helper = new state.HELPER();
        var mySpy = sinon.spy(helper, "fetchState");
    
        helper.pollStatus(mySpy,'80000', false);
        expect(mySpy.called).to.be.true;
        this.clock.tick(80000);
        expect(mySpy.called).to.be.true;
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      • 1970-01-01
      • 2018-12-04
      相关资源
      最近更新 更多