简体   繁体   English

如何在Sinon中存根匿名函数?

[英]How can I stub an anonymous function in Sinon?

The following: 下列:

const sinon = require('sinon')

const a = () => { return 1 }
sinon.stub(a)

throws TypeError: Attempted to wrap undefined property undefined as function . 抛出TypeError: Attempted to wrap undefined property undefined as function

stub works if there is an object, so I tried using this . 如果有一个对象, stub工作,所以我尝试使用this In node.js REPL (v6.11): 在node.js REPL(v6.11)中:

> const a = () => { return 1 }
undefined
> this.a
[Function: a]

However, in my mocha spec, it fails: 但是,在我的mocha规范中,它失败了:

const a = () => { return 1 }                                        

console.log(a)
// => [Function: a]

console.log(this.a)
// => undefined

What am I missing? 我错过了什么? How can I make this work? 我怎样才能做到这一点?

BTW: I'm aware that I can stub a method of an object, like this: const stub = sinon.stub(object, 'a') , but that's not what I'm after here with this question. 顺便说一句:我知道我可以stub一个对象的方法,比如: const stub = sinon.stub(object, 'a') ,但这不是我在这里提出的问题。

You can't make it work like this. 你无法让它像这样工作。 For stubbing, Sinon requires a "root object" because it needs to replace the function reference that you want to stub in that root object. 对于存根,Sinon 需要一个“根对象”,因为它需要替换要在该根对象中存根的函数引用。 The this in the REPL only works because of how the REPL is implemented. REPLthis只能用于REPL的实现方式。 In latest node (v8), it no longer automatically binds functions to this like described. 在最新的节点(v8)中,它不再像所描述的那样自动将函数绑定this

sinon.stub takes in an object and then you can stub the properties. sinon.stub接受一个对象然后你可以存根属性。 So you should be able to do 所以你应该能做到

const obj = {
  a: (() => return 1; })
};

and then be able to call 然后就可以打电话了

const stub = sinon.stub(obj, "a");

As you witnessed, you set const a to be a function in your example -- it needs to be an object and then sinon can stub a specific property in that object. 正如您所见,您将const a设置为示例中的函数 - 它需要是一个对象,然后sinon可以存根该对象中的特定属性。 I believe the reason for this is it then gives it something sinon can reference hence why sinon can also support things like object.method.restore() . 我相信这样做的原因是它给了它一些sinon可以引用的东西,因此sinon也可以支持像object.method.restore()这样的东西。

Another workaround is to bind to this on your own (although that's not recommended): 另一个解决方法是绑定到this你自己(虽然不推荐):

const a = () => { return 1 }
this.a = a;

sinon.stub(this, 'a').returns(2);
console.log(this.a());
// => 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM