Search code examples
javascriptunit-testingsinonstub

sandbox stub different stub withargs and callback


i would like stub one function and return a different value with different args and this fuction use one callback

ex:

function saop (){
 saop.get('car',"http://webservice.com",function (err, result) {});
// (null, {car:"car"}) 
 saop.get('house',"http://webservice.com",function (err, result) {});
// (null, {house:"house"})
}

i'm try use this :

var stub = sandbox.stub(saop, 'get');

stub.onCall(0).returns(null, {car:"car"});
stub.onCall(1).returns(null, {house:"house"});

but stub return always null, {car:"car"} i'm also try use :

var stub = sandbox.stub(saop, 'get');
 stub.withArgs('car').returns(null, {car:"car"});
 stub.withArgs('house').returns(null, {house:"house"});

but the stub return null.

can you for your help.


Solution

  • If you mean that the stub should call the callback with those values, you should use yields instead of returns (the former will call the first function argument it receives, in this case the callback, with the fixtures; the latter will actually make the function return those values, which in case of callbacks isn't very useful):

    stub.onCall(0).yields(null, {car:"car"});
    stub.onCall(1).yields(null, {house:"house"});