简体   繁体   中英

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 .

stub works if there is an object, so I tried using this . In node.js REPL (v6.11):

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

However, in my mocha spec, it fails:

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.

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. The this in the REPL only works because of how the REPL is implemented. In latest node (v8), it no longer automatically binds functions to this like described.

sinon.stub takes in an object and then you can stub the properties. 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. 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() .

Another workaround is to bind to this on your own (although that's not recommended):

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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