Sinon stubbing函数作为parameter passing

我有以下的示例类:

function Example() {...} Example.prototype.someFunc1() {...} Example.prototype.someFunc2() {...} Example.prototype.func(func) {var res = func(); ...} 

我通常调用Example#func() ,如下所示:

 var example = new Example(); example.func(example.someFunc1) // or like this, depending on what I want example.func(example.someFunc2) 

现在我在我的testing中存根Example#someFunc1()如下:

 var example = new Example(); sinon.stub(example, 'someFunc1').returns(...); exmaple.func(example.someFunc1); 

问题是Example#someFunc1()没有被这种方式存根并被正常调用。 在这种情况下我能做些什么?

在你的例子中,你保存对函数的引用。 然后你把它存根

您传递的是对原始函数的引用,而不是存根函数。

当存根时,存根的function不会消失 – 这就是为什么您可以稍后restore() 。 您或者需要传递对象的函数本身的引用,例如,

 sinon.stub(example, 'opt1').returns(42); example.logic([3, 2], example.opt1); 

或者传递一个对存根的引用,例如,

 var fn = sinon.stub(example, 'opt1').returns(42); example.logic([3, 2], fn); 

后者虽然没有任何意义上的testing, 你可以通过任何函数,没有任何理由残缺。

FWIW,你的小提琴远不及您发布的原始代码。


目前还不清楚你要testing什么:你传递一个函数引用 – 这可能是任何旧的函数,无论它是否附加到Example对象,例如,一个匿名函数就可以。

如果被测函数本身称为桩函数,则桩是有意义的。