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
Better solution instead of sinon.timers is use of es6 - Promises:
//Simple EventEmitter
let emitEvent = ( eventType, callback ) => callback( eventType )
//Test case
it('Try to test ASYNC event emitter', () => {
let mySpy = sinon.spy() //callback
return expect( new Promise( resolve => {
//event happends in 300 ms
setTimeout( () => { emitEvent('Event is fired!', (...args) => resolve( mySpy(...args) )) }, 300 ) //call wrapped callback
} )
.then( () => mySpy.args )).to.eventually.be.deep.equal([['Event is fired!']]) //ok
})
As you can see, the key is to wrap calback with resolve: (... args) => resolve (mySpy (... args)).
Thus, PROMIS new Promise().then() is resolved ONLY after will be called callback.
But once callback was called, you can already test, what you expected of him.
The advantages: