我遇到了一个我不明白的问题。我发出的事件在我的测试中没有被捕获。以下是以下代码 ( event.js
):
var util = require('util'),
proc = require('child_process'),
EventEmitter = require('events').EventEmitter;
var Event = function() {
var _self = this;
proc.exec('ls -l', function(error, stdout, stderr) {
_self.emit('test');
console.log('emitted');
});
};
util.inherits(Event, EventEmitter);
module.exports = Event;
以及相应的测试:
var proc = require('child_process'),
sinon = require('sinon'),
chai = require('chai'),
expect = chai.expect,
Event = require('./event'),
myEvent, exec;
var execStub = function() {
var _self = this;
return sinon.stub(proc, 'exec', function(cmd, callback) {
_self.cmd = cmd;
console.log(cmd);
callback();
});
};
describe('Event', function() {
beforeEach(function(){
exec = execStub();
});
afterEach(function(){
exec.restore();
});
it('Event should be fired', function(done) {
myEvent = new Event();
myEvent.on('test', function() {
expect(exec.cmd).to.equal('ls -l');
done();
});
});
});
现在,这是我所看到的:
- 该事件实际上是在测试期间发出的,因为
console.log('emitted');
发生了 - 该
exec
函数实际上是存根的,因为console.log(cmd);
发生
但是测试因超时而失败,并显示错误消息:
~ % mocha --timeout 15000 -R spec event.test.js
Event
◦ Event should be fired: ls -l
emitted
1) Event should be fired
0 passing (15 seconds)
1 failing
1) Event Event should be fired:
Error: timeout of 15000ms exceeded
at null.<anonymous> (/usr/lib/node_modules/mocha/lib/runnable.js:165:14)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
如果我从测试中删除存根,测试运行正常。如果我增加超时我仍然有同样的问题。
知道我做错了什么吗?
问候