Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test event emitters in node

Lets say I want to write this simple task. But I want to write a test validating that:

  1. This task emits object.
  2. Object has a property name.

I'm testing with mocha and chai expect.

Thanks in advance. I've tried every possible variant that came to mind, but could not come up with a solution.

var util = require('util'),     EventEmitter = require('events').EventEmitter;  function SomeTask() {   var self = this;    setInterval(function() {     self.emit('data', { name: 'name' });   }, 5000); }  util.inherits(SomeTask, EventEmitter);  module.exports = SomeTask; 
like image 545
datogio Avatar asked Nov 30 '14 01:11

datogio


People also ask

How do you test for EventEmitter?

We can take three approaches to testing the behavior of the EventEmitter from the perspective of the parent (the component listening for the event): Invoke the @Output property's emit method (since the EventEmitter is a public property) Dig in to the counter's DebugElement and simulate a click on the button.

How do I use event emitters in node JS?

Unit Testing and Test Driven Development in NodeJS 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.

What is event emitter in node JS?

The EventEmitter is a module that facilitates communication/interaction between objects in Node. EventEmitter is at the core of Node asynchronous event-driven architecture. Many of Node's built-in modules inherit from EventEmitter including prominent frameworks like Express.

How are events fired in node JS?

The EventEmitter Object To fire an event, use the emit() method.


1 Answers

Here's an example using spies. https://github.com/mochajs/mocha/wiki/Spies

var sinon = require('sinon'); var EventEmitter = require('events').EventEmitter;  describe('EventEmitter', function(){   describe('#emit()', function(){     it('should invoke the callback', function(){       var spy = sinon.spy();       var emitter = new EventEmitter;        emitter.on('foo', spy);       emitter.emit('foo');       spy.called.should.equal.true;     })      it('should pass arguments to the callbacks', function(){       var spy = sinon.spy();       var emitter = new EventEmitter;        emitter.on('foo', spy);       emitter.emit('foo', 'bar', 'baz');       sinon.assert.calledOnce(spy);       sinon.assert.calledWith(spy, 'bar', 'baz');     })   }) }) 
like image 65
Miguel Mota Avatar answered Sep 23 '22 19:09

Miguel Mota