Calling different callbacks for stub on firstcall and second call

Rajesh Nagpal picture Rajesh Nagpal · Jun 3, 2016 · Viewed 15.5k times · Source

I'm looking for a way in sinon to call different functions in first and second call to the stub method.

Here is an example:

var func1 = function(connectionPolicy, requestOptions, callback) {
 callback({ code: 403 });
 }

var func2 = function (connectionPolicy, requestOptions, callback) {
 callback(undefined);
 }


var stub = sinon.stub();

// Something of this form

 stub.onCall(0) = func1;

 stub.onCall(1) = func2;

request.createRequestObjectStub = stub;

So that when request.createrequestObjectStub gets called internally(when calling a public API), I see this behavior.

Regards, Rajesh

•Sinon version : 1.17.4 •Environment : Node JS

Answer

elbecita picture elbecita · Jun 6, 2016

The only way I found to do what you want (with onCall(index) and an anonymous stub) is with bind JS Function.

This would be:

stub.onCall(0).returns(func1.bind()());
stub.onCall(1).returns(func2.bind()());

If you use stub.onCall(0).returns(func1()); the function func1 is executed when defining that onCall, that is why you need the .bind.

Anyway, you have other options, like returning a value directly with .onCall(index).returns(anObject); or defining a counter that is incremented each time your stubbed method is called (this way you know in which n-call you are and you can return different values).

For these three approaches, you can see the following fiddle with examples: https://jsfiddle.net/elbecita/jhvvv1h1/