Search code examples
javascriptunit-testingqunitsinon

How to test the function call count of another function in Javascript?


Say I have this function:

function doSomething(n) {
    for (var i = 0; i < n; i++) {
        doSomethingElse();
    }
}

How would I test if the doSomethingElse function is called n times??

I tried something like:

test("Testing something", function () {
    var spy = sinon.spy(doSomethingElse);

    doSomething(12);

    equal(spy.callCount, 12, "doSomethingElse is called 12 times");
});

but this does not seem to work, because you have to call the spy while the doSomething() calls the original doSomethingElse(). How can I make this work with QUnit/sinon.js?

EDIT

Maybe it isn't even a good idea? Does this fall outside the 'unit testing' because another function is called?


Solution

  • You could do something like this:

    test('example1', function () {
        var originalDoSomethingElse = doSomethingElse;
        doSomethingElse = sinon.spy(doSomethingElse);
        doSomething(12);
        strictEqual(doSomethingElse.callCount, 12);
        doSomethingElse = originalDoSomethingElse;
    });
    

    For example: JSFiddle.