【问题标题】:Sinon stubbing a function passed as a parameterSinon 存根作为参数传递的函数
【发布时间】:2016-08-20 14:31:12
【问题描述】:

我有以下示例类:

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() 没有以这种方式被存根并被正常调用。在这种情况下我该怎么办?

【问题讨论】:

标签: javascript node.js testing sinon stub


【解决方案1】:

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

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

你存根的函数不会在你存根时消失——这就是你以后可以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,您的小提琴与您发布的原始代码相差甚远。


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

如果被测函数本身调用了存根函数,那么存根是有意义的。

【讨论】:

  • 是的,我不知道自己在想什么.. 谢谢 :)
猜你喜欢
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 2017-02-21
相关资源
最近更新 更多