I\'m writing a bunch of mocha tests and I\'d like to test that particular events are emitted. Currently, I\'m doing this:
it(\'should emit an some_event\', fun
This method ensures the minimum time to wait but the maximum opportunity as set by the suite timeout and is quite clean.
it('should emit an some_event', function(done){
myObj.on('some_event', done);
});
Can also use it for CPS style functions...
it('should call back when done', function(done){
myAsyncFunction(options, done);
});
The idea can also be extended to check more details - such as arguments and this
- by putting a wrapper arround done
. For example, thanks to this answer I can do...
it('asynchronously emits finish after logging is complete', function(done){
const EE = require('events');
const testEmitter = new EE();
var cb = sinon.spy(completed);
process.nextTick(() => testEmitter.emit('finish'));
testEmitter.on('finish', cb.bind(null));
process.nextTick(() => testEmitter.emit('finish'));
function completed() {
if(cb.callCount < 2)
return;
expect(cb).to.have.been.calledTwice;
expect(cb).to.have.been.calledOn(null);
expect(cb).to.have.been.calledWithExactly();
done()
}
});