如何在Javascript中测试另一个函数的函数调用计数?

问题描述 投票:3回答:5

说我有这个功能:

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

我如何测试doSomethingElse函数是否被调用过n次?

我尝试过类似的事情:

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

    doSomething(12);

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

但是这似乎不起作用,因为您必须在doSomething()调用原始doSomethingElse()时调用间谍。如何使用QUnit / sinon.js使其工作?

编辑

也许这不是个好主意?因为调用了另一个函数,这是否属于“单元测试”范围之外?

javascript unit-testing qunit sinon
5个回答
5
投票

您可以执行以下操作:

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

例如:JSFiddle


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

您无法监视doSomethingElse。

doSomethingElse不可测试,当某些内容不可测试时,需要对其进行重构。

您需要在doSomething中注入doSomethingElse

OR

使用指针:

pointer={doSomethingElse:function(){}};

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

0
投票

声明一个名为count的全局变量,并将其分配给0

window.count = 0;

现在,在doSomethingElse()函数内部,使其像count++一样递增>

因此,每当您访问count变量时,它将返回调用doSomethingElse()的次数。

完整代码可能是:

window.count = 0;

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

function doSomethingElse() {
    count++;
    // do something here
}

doSomething(22);
alert(count);// alerts 22

甚至更好的是,只要要在代码中调用要测试的函数,就调用count++

演示:http://jsfiddle.net/583ZJ/

注意:

如果要删除它,则只需删除变量声明(window.count=0;)和count++

0
投票
function debugCalls(f) {
    if (!f.count) 
        f.count = 0;

    f.count++;
}

function doSomethingElse()
{
    debugCalls(arguments.callee);


    // function code...
}


// usage
for(var i = 0; i < 100; i++) doSomethingElse();

alert(doSomethingElse.count);

0
投票

在Node.js 14.2.0中,无需使用Sinon或其他附加库,就可以使用新的试验性CallTracker API来完成这项工作。

© www.soinside.com 2019 - 2024. All rights reserved.