测试抛出错误的异步函数时catchError代码块无覆盖率问题求解
问题根因
你当前的测试直接mock了updateContact方法本身,执行测试时调用的是你模拟的抛错逻辑,完全没有运行你写的updateContact原始实现,自然不会触发catchError块内的代码,所以这部分不会被计入覆盖率统计。
解决方法
你需要改为mock底层的httpService.put方法,让它抛出错误触发原始方法内的错误处理逻辑,修改后的测试参考如下:
const contactId = 1; const authToken = 'Bearer f4k3-70k3n'; const data = { policy_id: 2 }; it('should throw NotFoundException', async () => { // 替换为你测试模块中注入的httpService实例 jest.spyOn(httpService, 'put').mockReturnValueOnce( // 模拟http请求抛出错误 throwError(() => new NotFoundException()) ); // 直接调用原始updateContact方法,不要mock该方法 await expect(sessionService.updateContact(contactId, authToken, data)).rejects.toThrowError(NotFoundException); // 可选:验证http方法调用参数符合预期 expect(httpService.put).toHaveBeenCalledWith( `${yourMockedConfig.customer.url}/contacts/${contactId}`, data, { headers: { Authorization: authToken } } ); });
额外注意事项
- 提前在测试模块中mock好
config依赖的取值,避免url拼接时出现未定义变量报错 - 如果需要验证
console.dir逻辑的执行,可以额外mockconsole.dir方法,断言该方法被正确调用
内容的提问来源于stack exchange,提问作者octavemirbeau
相关产品推荐
相关产品推荐

