title: how to unit test uncaughtException and unhandledRejection in Nodejs using Jest
body: <p>I have built an error handler like this:</p>
  <pre class="lang-js prettyprint-override"><code>const logger = require('./logger');
  
  module.exports = () =&gt; {
    process.on('uncaughtException', (err) =&gt; {
      logger.error(err.message, err);
      process.exit(1);
    });
  
    process.on('unhandledRejection', (err) =&gt; {
      throw err;
    });
  };
  </code></pre>
  <p>Now I want to unit test this, mainly the first event listener. My current test looks like this:</p>
  <pre class="lang-js prettyprint-override"><code>const logger = require('../../utils/logger');
  require('../../utils/unhandledErrors')();
  
  describe('Uncaught Exceptions', () =&gt; {
    it('should log the exception and exit the process', () =&gt; {
      process.exit = jest.fn();
      logger.error = jest.fn();
      jest.fn(() =&gt; {
        throw new Error('fake error');
      })();
  
      expect(logger.error).toBeCalledTimes(1);
      expect(process.exit).toBeCalledTimes(1);
      expect(process.exit).toBeCalledWith(1);
    });
  });
  </code></pre>
  <p>The code above fails at throw new error line with no useful information logged to console by jest despite the --verbose flag.<br />
  Any suggestions on how to unit test such modules? I have looked through the link below but found nothing.<br />
  <a href="https://stackoverflow.com/questions/52493145/how-to-test-a-unhandledrejection-uncaughtexception-handler-with-jest">How to test a unhandledRejection / uncaughtException handler with jest</a></p>