Javascript 使用 sinon spies 验证函数调用和检查参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29800733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:01:09  来源:igfitidea点击:

Verifying function call and inspecting arguments using sinon spies

javascriptunit-testingsinon

提问by filur

I would like to verify that bar()is called inside foo()from my unit test.

我想验证它bar()foo()从我的单元测试中调用的。

I figured that Sinon spiesmight be suitable, but I don't know how to use them.

我觉得诗乃间谍可能很合适,但我不知道如何使用它们。

Is there any way to check that the method is called? Perhaps even extracting the arguments used in the bar()call?

有没有办法检查该方法是否被调用?甚至可能提取调用中使用的参数bar()

var spy = sinon.spy(foo);

function foo(){
    bar(1,2,3);
}

function bar(){ }

foo();

// what to do with the spy?

http://jsfiddle.net/8by9jg07/

http://jsfiddle.net/8by9jg07/

回答by phtrivier

In your case, you are trying to see if barwas called, so you want to spy barrather than foo.

在您的情况下,您正在尝试查看是否bar被调用,因此您想要监视bar而不是foo.

As described in the 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]

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.

现在,监视函数的内部结构会将您对“foo”的测试与其实现紧密结合在一起,因此您将陷入通常的“模拟者与经典”辩论中。

回答by user1699348

I agree with Adrian in saying that you probably wanted to spy on bar instead.

我同意 Adrian 的说法,您可能想改为监视酒吧。

var barSpy = sinon.spy(bar);

Then to check that it was called once

然后检查它是否被调用过一次

assert(barSpy.calledOnce);

Just called at all

刚刚打电话

assert(barSpy.called)

Called x amount of times

被调用 x 次

assert.equal(barSpy.callCount, x);

If you want to extract the arguments from the first call of the spy:

如果你想从间谍的第一次调用中提取参数:

var args = barSpy.getCalls()[0].args

Then you can do what you want with those arguments.

然后你可以用这些参数做你想做的事。

回答by Adrian Lynch

Shouldn't you be spying on bar, rather than foo?

你不应该监视 bar 而不是 foo 吗?

var spy = sinon.spy(bar)

Call foo:

调用 foo:

foo()

Check bar was called:

检查栏被称为:

console.log(spy.calledOnce)