使用sinon间谍验证函数调用和检查参数 [英] Verifying function call and inspecting arguments using sinon spies
问题描述
我想验证 bar()
是否来自我的单元测试 foo()
。
I would like to verify that bar()
is called inside foo()
from my unit test.
我认为 Sinon间谍可能会是合适的,但我不知道如何使用它们。
I figured that Sinon spies might be suitable, but I don't know how to use them.
有没有办法检查方法是否被调用?甚至可能提取 bar()
中使用的参数?
Is there any way to check that the method is called? Perhaps even extracting the arguments used in the bar()
call?
var spy = sinon.spy(foo);
function foo(){
bar(1,2,3);
}
function bar(){ }
foo();
// what to do with the spy?
推荐答案
在您的情况下,您正试图查看是否 bar
被调用,所以你想窥探 bar
而不是 foo
。
In your case, you are trying to see if bar
was called, so you want to spy bar
rather than foo
.
如 doc 中所述:
function bar(x,y) {
console.debug(x, y);
}
function foo(z) {
bar(z, z+1);
}
// Spy on the function "bar" of the global object.
var spy = sinon.spy(window, "bar");
// Now, the "bar" function has been replaced by a "Spy" object
// (so this is not necessarily what you want to do)
foo(1);
bar.getCall(0).args => should be [1,2]
现在,监视函数的内部强烈地结合你的测试foo到它的实现,所以你将落入通常的mockist vs classical辩论。
Now, spying on the internals of the function strongly couples your test of "foo" to its implementation, so you'll fall into the usual "mockist vs classical" debate.
这篇关于使用sinon间谍验证函数调用和检查参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!