Jorayen Jorayen - 1 year ago 94
Node.js Question

Sinon stubbing a function passed as a parameter

I have the following Example class:

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

I usually call
as follows:

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

Now I stub
as follows in my test:

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

Problem is that
is not being stubbed this way and being called normally. What can I do in such situation ?

Answer Source

In your example you save a reference to the function. Then you stub it.

You're passing a reference to the original function, not the stubbed function.

The function you stub does not disappear when you stub it–that's why you can restore() it later. You either need to pass a reference to object's function itself, e.g.,

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

Or pass a reference to the stub, e.g.,

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

The latter doesn't really make any sense as a test, though; you could just pass in any function, there's no reason to stub anything.

FWIW, your fiddle is nowhere near equivalent to the original code you posted.

It's unclear what you're trying to test: you pass a function reference–this could be any old function, whether or not it's attached to the Example object, e.g., an anonymous function would be fine.

If the function under test itself called the stubbed function, stubbing makes sense.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download