如何用玩笑来测试unhandledRejection / uncaughtException处理程序

问题描述 投票:6回答:1

我有unhandledRejectionuncaughtException的处理程序:

bin.js

['unhandledRejection', 'uncaughtException'].forEach(event => {
  process.on(event, err => logger.error(err));
});

现在我想用jest测试它们:

bin.test.js

const bin = require('../bin');

test('catches unhandled rejections', async () => {
  const error = new Error('mock error');
  await Promise.reject(error);
  expect(logger.error).toHaveBeenCalledWith(error);
});

test('catches uncaught exceptions', () => {
  const error = new Error('mock error');
  throw error;
  expect(logger.error).toHaveBeenCalledWith(error);
});

但是jest只是告诉我测试中有错误:

●收到未处理的拒绝

mock error

   8 | // https://github.com/facebook/jest/issues/5620
   9 | test('catches unhandled rejections', async () => {
> 10 |   const error = new Error('mock error');
     |                 ^
  11 |   await Promise.reject(error);
  12 |   expect(logger.error).toHaveBeenCalledWith(error);
  13 | });

  at Object.<anonymous>.test (test/bin.test.js:10:17)

●捕获未捕获的异常

mock error

  14 |
  15 | test('catches uncaught exceptions', () => {
> 16 |   const error = new Error('mock error');
     |                 ^
  17 |   throw error;
  18 |   expect(logger.error).toHaveBeenCalledWith(error);
  19 | });

  at Object.<anonymous>.test (test/bin.test.js:16:17)

有没有一种方法可以测试?

可能与此相关:https://github.com/facebook/jest/issues/5620

javascript unit-testing jestjs
1个回答
0
投票

将其放入try catch中将有所帮助:

const error = new Error('mock error');

尝试{

await Promise.reject(error);

}抓住(错误){

   expect(logger.error).toHaveBeenCalledWith(error);

}

© www.soinside.com 2019 - 2024. All rights reserved.