manalang manalang - 3 months ago 14
Node.js Question

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

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', function(done){
myObj.on('some_event',function(){
assert(true);
done();
});
});


However, if the event never emits, it crashes the test suite rather than failing that one test.

What's the best way to test this?

Answer

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){
  var errTimeout = setTimeout(function () {
    assert(false, 'Event never fired'); //or assert.fail, or whatever.
    done(); //I don't remember whether or not you still supposed to call done()
  }, 1000); //timeout with an error in one second

  myObj.on('some_event',function(){
    clearTimeout(errTimeout); //cancel error timeout
    assert(true);
    done();
  });
});

Make sure your timeout setting in Mocha is at least as high as the timeout you use in the code here.

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