简体   繁体   English

如何在节点中测试事件发射器

[英]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. Object具有属性名称。

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;

Here's an example using spies. 这是一个使用间谍的例子。 https://github.com/mochajs/mocha/wiki/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');
    })
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM