How to test event emitters in node

 ̄綄美尐妖づ 提交于 2019-12-03 08:22:17

问题


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;

回答1:


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


来源:https://stackoverflow.com/questions/27209016/how-to-test-event-emitters-in-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!