Jorayen Jorayen - 3 months ago 11
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
Example#func()
as follows:

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


Now I stub
Example#someFunc1()
as follows in my test:

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


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

Answer

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.