What's the best way to unit test an event being emitted in Nodejs?

后端 未结 7 647
孤独总比滥情好
孤独总比滥情好 2021-02-05 02:12

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         


        
7条回答
  •  北海茫月
    2021-02-05 02:21

    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:

    • we dont need to guess timeout to wait until event is fired (in case of many describes() and its()), not depending on perfomance of computer
    • and tests will be faster passing

提交回复
热议问题