Javascript 如何在节点中测试事件发射器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27209016/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test event emitters in node
提问by datogio
Lets say I want to write this simple task. But I want to write a test validating that:
假设我想编写这个简单的任务。但我想编写一个测试来验证:
- This task emits object.
- Object has a property name.
- 此任务发出对象。
- 对象具有属性名称。
I'm testing with mocha and chai expect.
我正在用 mocha 和 chai 进行测试。
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;
回答by Miguel Mota
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');
})
})
})

