2016-04-28 88 views
1

我試圖編寫一個單元測試setInterval(),但我不知道如何窺探fetchState()如何測試設置在sinon js的時間間隔

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

回答

3

間諜未註冊到的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; 
}); 
相關問題