15

I am trying to stub the following:

on('complete', function(data){ });

I only want to call the callback if the first parameter is 'complete'.

The function I am testing also contains:

on('error', function(data){ });

So I can't just do yield cause that will fire both the complete and the error callback.

If I wouldn't use sinon I would fake it by writing the following.

var on = function(event, callback){
  if (event === 'complete'){
    callback('foobar');
  };
};
Pickels
  • 33,902
  • 26
  • 118
  • 178

2 Answers2

9

You can narrow the circumstances under which a yield occurs by combining it with a withArgs like so...

on.withArgs('complete').yields(valueToPassToCompleteCallback);
on.withArgs('error').yields(valueToPassToErrorCallback);
philipisapain
  • 886
  • 9
  • 13
0

Maybe you can use a spyCall:

var spy = sinon.spy(window, 'on');
on('error', function(data){ });
on('complete', function(data){ });
for(var i=0; i < spy.callCount; i++){
    var call = spy.getCall(i);
    if(call.args[0] === 'complete') call.args[1]('foobar');
}
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297