Sinon 存根作为参数传递的函数

Sinon stubbing a function passed as a parameter

我有以下例子class:

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)

现在我在测试中存根 Example#someFunc1() 如下:

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

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

在您的示例中,您保存了对该函数的引用。然后你存根。

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

存根的函数在存根时不会消失——这就是为什么以后可以 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);

虽然后者作为测试没有任何意义;您可以传入任何函数,没有理由存根。

FWIW,您的 fiddle 远不等同于您发布的原始代码。


不清楚您要测试什么:您传递了一个函数引用——这可以是任何旧函数,无论它是否附加到 Example 对象,例如,匿名函数就可以了.

如果被测函数本身调用了存根函数,存根就有意义了。