Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
  };
};
like image 303
Pickels Avatar asked May 14 '12 17:05

Pickels


People also ask

How do I stub an object in Sinon?

Stubbing functions in a deeply nested object getElementsByTagName as an example above. How can you stub that? The answer is surprisingly simple: var getElsStub = sinon.

How do you stub a promise in Sinon?

To stub a promise with sinon and JavaScript, we can return a promise with a stub. import sinon from "sinon"; const sandbox = sinon. sandbox. create(); const promiseResolved = () => sandbox.

How does Sinon stub work?

Sinon replaces the whole request module (or part of it) during the test execution, making the stub available via require('request') and then restore it after the tests are finished? require('request') will return the same (object) reference, that was created inside the "request" module, every time it's called.

How do I use event emitters in node JS?

Many objects in a Node emit events, for example, a net. Server emits an event each time a peer connects to it, an fs. readStream emits an event when the file is opened. All objects which emit events are the instances of events.


1 Answers

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);
like image 168
philipisapain Avatar answered Sep 20 '22 20:09

philipisapain