Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 594
manalang Avatar asked May 30 '13 01:05

manalang


People also ask

How do I emit an event in Node JS?

EventEmitter Class When a new listener is added, 'newListener' event is fired and when a listener is removed, 'removeListener' event is fired. EventEmitter provides multiple properties like on and emit. on property is used to bind a function with the event and emit is used to fire an event.

What is the best testing framework for Nodejs?

What are the best Node. js unit testing frameworks? According to “The State of JavaScript 2021,” the most popular JavaScript testing frameworks and libraries in 2021 were Testing Library, Vitest, Jest, Cypress, Playwright, and Storybook. Rounding out the top ten are Puppeteer, Mocha, Jasmine, AVA, and WebdriverIO.

What will be used for unit testing in node JS?

Jest is one of the most popular unit testing tools, for JavaScript in general and also for Node. js.


1 Answers

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.

like image 186
Bret Copeland Avatar answered Sep 27 '22 21:09

Bret Copeland