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?
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 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.
Jest is one of the most popular unit testing tools, for JavaScript in general and also for Node. js.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With