Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 337
devqon Avatar asked Apr 26 '26 01:04

devqon


1 Answers

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.

like image 175
psquared Avatar answered Apr 27 '26 13:04

psquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!