How do I stub an event emitter with Sinon.js

Pickels picture Pickels · May 14, 2012 · Viewed 8.5k times · Source

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

Answer

philipisapain picture philipisapain · Jul 24, 2015

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