How do I stub an event emitter with Sinon.js

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');
  };
};

Answers:

Answer

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);
Answer

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');
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.