Lets say I want to write this simple task. But I want to write a test validating that:
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;
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.
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.
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.
The EventEmitter Object To fire an event, use the emit() method.
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'); }) }) })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With