您有点在正确的道路上,但偏离了方向。让我们逐步完成您的工作并把事情做好:
// ...
function myFunc() {
console.log( 'hello' );
}
var spiedMyFunc = sinon.spy( myFunc ); // what you want is a 'spy' not a 'stub'
// ...
然后在这一点上spiedMyFunc 包裹myFunc。因此,调用spiedMyFunc() 应该在很大程度上相当于与调用myFunc() 的结果相同。同时spiedMyFunc另外
记录所有参数、这个值、异常和返回值
来电。
所以剩下的sn-p代码应该如下:
// myFunc(); // no you should be calling spiedMyFunc() instead
spiedMyFunc();
expect( spiedMyFunc.called ).to.be.true();
这就是您监视独立函数的方式。但是,存根独立函数在概念上没有意义。
在对此答案的评论中回答@charlesdeb 的问题:
当一个方法被调用时,它可以触发一个隐式调用其他方法的链。由于这种隐式或间接调用,您可能希望控制链中其他方法的行为,同时研究特定方法的行为。 存根是实现上述控制的一种手段。
在使用函数时,实际上遵循函数范式以使事情变得简单可靠是有益的。考虑一下:
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 );
如果您想存根a,那么不要使用真正的a 创建间谍,而是使用您喜欢的存根。
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 );