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

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

    If you can guarantee that the event should fire within a certain amount of time, then simply set a timeout.

    it('should emit an some_event', function(done){
      this.timeout(1000); //timeout with an error if done() isn't called within one second
    
      myObj.on('some_event',function(){
        // perform any other assertions you want here
        done();
      });
    
      // execute some code which should trigger 'some_event' on myObj
    });
    

    If you can't guarantee when the event will fire, then it might not be a good candidate for unit testing.

提交回复
热议问题