如何修复单元测试中的UNHANDLED_REJECTION错误?
单元测试UnhandledPromiseRejection错误解决办法
错误详情
测试执行失败,出现错误
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().]
核心原因
- 异步测试函数中抛出异常,但未添加
try/catch捕获 - 测试中调用了返回Promise的方法,Promise被拒绝但未通过
.catch()处理,也没使用测试框架的断言方法(如expect().rejects)
解决步骤
1. 针对async/await写法的测试函数
在异步测试函数中用try/catch包裹逻辑,或者直接使用测试框架的rejects断言:
// 方式一:try/catch捕获并断言 test('异步测试示例', async () => { try { await 你的异步函数(); } catch (err) { expect(err.message).toBe('预期的错误信息'); } }); // 方式二:使用rejects断言简化代码 test('异步测试示例', async () => { await expect(你的异步函数()).rejects.toThrow('预期的错误信息'); });
2. 针对Promise链式调用的测试
确保每个Promise链式调用都添加.catch(),或者用测试框架的rejects断言:
// 方式一:用rejects断言 test('Promise测试示例', () => { return expect(你的Promise函数()).rejects.toThrow('预期的错误信息'); }); // 方式二:手动添加catch并处理 test('Promise测试示例', (done) => { 你的Promise函数() .then(result => { expect(result).toBe(预期值); done(); }) .catch(err => { expect(err.message).toBe('预期的错误信息'); done(); }); });
3. 临时排查手段(不推荐长期使用)
如果不确定哪个Promise未处理,可以在测试代码开头添加全局监听定位问题:
process.on('unhandledRejection', (reason, promise) => { console.log('未处理的Promise拒绝原因:', reason); console.log('对应的Promise实例:', promise); });
内容的提问来源于stack exchange,提问作者sneha
相关产品推荐
相关产品推荐

