当我在对象内部的函数上使用Sinon时,它可以工作:
function myFunc() {
console.log('hello');
}
var myObj = { myFunc: myFunc };
var spy = sinon.stub(myFunc);
myObj.myFunc();
expect(spy.called).to.be.true();
Run Code Online (Sandbox Code Playgroud)
但是,我不知道为什么当我在独立函数上使用Sinon时如下:
function myFunc() {
console.log('hello');
}
var spy = sinon.stub(myFunc);
myFunc();
expect(spy.called).to.be.true();
Run Code Online (Sandbox Code Playgroud)
断言失败了.
Igw*_*alu 15
你在正确的道路上有点偏离但是偏离了.让我们一起努力,让事情正确:
// ...
function myFunc() {
console.log( 'hello' );
}
var spiedMyFunc = sinon.spy( myFunc ); // what you want is a 'spy' not a 'stub'
// ...
Run Code Online (Sandbox Code Playgroud)
然后在这一点spiedMyFunc包裹myFunc.因此,呼吁spiedMyFunc()应该大多达到相同的结果与调用myFunc().同时spiedMyFunc另外
记录所有调用的参数,此值,异常和返回值.
所以代码片段的其余部分应如下所示:
// myFunc(); // no you should be calling spiedMyFunc() instead
spiedMyFunc();
expect( spiedMyFunc.called ).to.be.true();
Run Code Online (Sandbox Code Playgroud)
这就是你如何窥探独立功能.但是,存储独立函数并不具有概念意义.
在对此答案的评论中回答@charlesdeb的问题:
调用方法时,它可以触发隐式调用其他方法的链.由于这种隐式或间接调用,您可能希望在研究特定方法的行为时控制链中其他方法的行为.*Stubbing*是实现所述控制的手段.
在使用函数时,实际遵循功能范例以使事情变得简单可靠是有益的.考虑一下:
function a () { ... }
function b () { a(); }
Run Code Online (Sandbox Code Playgroud)
在测试时b,有必要并且足以证明执行b()依次执行a().但随着方式的b实施,无法验证a被调用的方式.
但是,如果我们应用功能范例,那么我们就应该这样做
function a () { ... }
function b ( a ) { a(); }
Run Code Online (Sandbox Code Playgroud)
因此,我们可以编写如下的简单测试:
var a_spy = sinon.spy( a );
var actualOutcomeOfCallingB = b( a_spy );
expect( a_spy.called ).to.be.true;
expect( actualOutcomeOfCallingB ).to.equal( expectedOutcome );
Run Code Online (Sandbox Code Playgroud)
如果您想要存根 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 );
Run Code Online (Sandbox Code Playgroud)
您的第一个示例效果不佳。目前无法从独立函数创建存根。您可以存根对象的方法:
var stub = sinon.stub(myObj, 'myFunc');
Run Code Online (Sandbox Code Playgroud)
但是,如果您想监视方法或函数,则应该创建一个间谍(而不是存根):
窥探方法:
var spy = sinon.spy(myObj, 'myFunc');
myObj.myFunc(); // or spy();
expect(spy.called).to.be.true();
Run Code Online (Sandbox Code Playgroud)
监视独立功能:
var spy = sinon.spy(myFunc); // returns spied function
spy();
expect(spyFunc.called).to.be.true();
Run Code Online (Sandbox Code Playgroud)
请注意,它sinon.spy(myFunc)不会修改原始函数,它只是返回一个间谍。
| 归档时间: |
|
| 查看次数: |
9846 次 |
| 最近记录: |