Search code examples
javascriptmocha.jssinonsinon-chai

How to test set Interval in sinon js


I'm trying to write a unit test for setInterval(), but i'm not sure how to spy on the 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;
});

Solution

  • The spy is not registered to the setInterval. Your function fetchState should be passed as an parameter to the function.

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

    and your tests should look like this

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