ENV
ENV

Reputation: 1292

How to test process.on() using mocha?

Apologies if this is a naive question. I'm relatively new to Typescript and Mocha testing. I have the following processes which I want to test to increase code coverage:

process.on('unhandledRejection', (reason, p) => {
    LoggingService.error(reason, 'unhandledRejection', 'Unhandled Rejection at:');
});

process.on('uncaughtException', (error) => {
    LoggingService.error(error, 'unhandledRejection', 'Caught exception: ');
});

process.on('warning', (warning) => {
    LoggingService.info('Warning, Message: ' + warning.message + ' Stack: ' + warning.stack, 'warning');
});

process.on('exit', (code) => {
    LoggingService.error(null, 'NodeJs Exit', `Node.js process is about to exit with code: ${code}`);
});

How do I write tests in mocha for processes? In particular, if I want to simulate process.on for unhandledRejection, uncaughtException, warning, exit how would I be able to do that and what would I be expecting since there's no return statement for these processes?

Thanks in advance.

Upvotes: 0

Views: 1177

Answers (1)

antonku
antonku

Reputation: 7675

You can emit events on process object to test the event handlers. And you can spy on LoggingService object to check that methods are invoked with the expected arguments using a library like sinon.

This console.log based example shows the idea:

const sinon = require('sinon');

// This event handler is what we are going to test 
process.on('warning', () => {
  console.log('received warning');
});

describe('process', () => {
  it('should handle "warning" event', (done) => {
    const spy = sinon.spy(console, 'log');

    process.on('warning', () => {
      sinon.assert.calledWith(spy, 'received warning')
      done()
    });

    process.emit('warning')
  })
})

Upvotes: 5

Related Questions