gpt4 book ai didi

sinon spy on 独立功能

转载 作者:行者123 更新时间:2023-12-03 14:12:42 27 4
gpt4 key购买 nike

当我在对象内部的函数上使用 Sinon 时,它可以工作:

function myFunc() {
console.log('hello');
}
var myObj = { myFunc: myFunc };
var spy = sinon.stub(myFunc);
myObj.myFunc();
expect(spy.called).to.be.true();

但是,我不知道为什么当我在独立功能上使用 Sinon 时,如下所示:
function myFunc() {
console.log('hello');
}
var spy = sinon.stub(myFunc);
myFunc();
expect(spy.called).to.be.true();

断言失败。

最佳答案

你走在正确的道路上,但偏离了方向。让我们来看看你的努力并把事情做好:

// ...
function myFunc() {
console.log( 'hello' );
}
var spiedMyFunc = sinon.spy( myFunc ); // what you want is a 'spy' not a 'stub'
// ...
那么此时 spiedMyFunc包裹 myFunc .因此,调用 spiedMyFunc()应该是 金额为与调用 myFunc() 的结果相同.同时 spiedMyFunc此外

records arguments, this value, exceptions and return values for allcalls.


所以其余的代码片段应该如下所示:
// myFunc(); // no you should be calling spiedMyFunc() instead
spiedMyFunc();
expect( spiedMyFunc.called ).to.be.true();
这就是您监视独立功能的方式。但是, stub 独立函数在概念上没有意义 .

回复 @charlesdeb对此答案的评论中的问题:
当一个方法被调用时,它可以触发一个隐式调用其他方法的链。由于这种隐式或间接调用,您可能希望在研究特定方法的行为时控制链中其他方法的行为方式。 stub 是实现上述控制的一种手段。
在使用函数时,实际上遵循函数范式以使事情变得简单和可靠是有益的。考虑一下:
function a () { ... }

function b () { a(); }
测试时 b , 证明 b() 的执行是必要且充分的依次执行 a() .不过顺便 b已实现,无法验证 a被称为。
但是,如果我们应用函数范式,那么我们应该有
function a () { ... }

function b ( a ) { a(); }
因此,我们可以编写一个简单的测试,如下所示:
var a_spy = sinon.spy( a );

var actualOutcomeOfCallingB = b( a_spy );

expect( a_spy.called ).to.be.true;
expect( actualOutcomeOfCallingB ).to.equal( expectedOutcome );
如果你想 stub a , 然后用真实的 a 创建 spy 而不是使用您喜欢的 stub 执行此操作。
var a_stub = sinon.spy( function () { /* behaves differently than the actual `a` */ }  ); // that's your stub right there!

var actualOutcomeOfCallingB = b( a_stub );

expect( a_stub.called ).to.be.true;
expect( actualOutcomeOfCallingB ).to.equal( expectedOutcome );

关于sinon spy on 独立功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32321149/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com