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

后端 未结 7 670
孤独总比滥情好
孤独总比滥情好 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:34

    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()
        }
    
    });
    

提交回复
热议问题