Monday 12 June 2017

setInterval() not working mocha test

Background

I have a heartbeat object that once started calls a function every X milliseconds.

My objective is to test if my heartbeat object is actually calling the said function and I am using mocha to test it.

Code

heartbeat.js

const heartBeat = () => {
    let timer;

    const start = fn => {
        timer = setInterval(fn, 500);
    };

    return {
        start
    };
};

module.exports = heartBeat;

test.js

describe("heartBeat", () => {

    const heartBeat = heartBeatFactory();

    it("should call the 'Fn' 2 times after start", done => {
        let cnt = 0;

        const testFn = () => {
            console.log("Hello World");
            cnt++;
        };

        setTimeout(() => {
            if(cnt === 2)
                done();
        }, 1350);

        heartBeat.start(testFn);
    });

});

Problem

According to the code, I should be able to see "Hello World" printed two times.

Not only that, but after 1350ms, the test should also conclude successfully.

However, nothing is printed, and the test is timing out. What am I doing wrong?



via Flame_Phoenix

No comments:

Post a Comment