StevenR StevenR - 8 months ago 111
Node.js Question

When using Sinon, how to replace stub function in a stub instance?

If I have create a instance by

var a = sinon.createStubInstance(MyContructor)

How can I replace one of the stubbed function like
var stub = sinon.stub(object, "method", func);

The main reason I am doing this is want to achieve multiple callback workaround as this mentioned


I don't think this does make a lot of sense, because if you're replacing a stub with another stub... then why don't you just use the first stub to achieve whatever you want to do with the second stub.

Anyways, the sinon.stub(object, "method", func) does the following according to the docs:

Replaces object.method with a func, wrapped in a spy. As usual, object.method.restore(); can be used to restore the original method.

So, if you want to replace a stub function of a stub instance, then why don't you do:

var a = sinon.createStubInstance(MyConstructor);
a.method = sinon.spy(function() { return "Foo Bar"; });

Or if you want to create a stub in stead of a spy:

var a = sinon.createStubInstance(MyConstructor);
a.method = sinon.stub();