JEST测试异常:异步函数未抛出预期错误的问题排查
问题分析与解决方案
你的测试失败的核心原因是axios未被正确Mock,导致代码实际发送了真实API请求而非触发你预设的拒绝状态,因此fetchRate没有进入catch块抛出预期错误。
以下是具体解决步骤:
1. 正确Mock axios模块
在测试文件顶部添加Mock声明,让Jest使用模拟版本的axios,而非真实网络请求模块:
jest.mock('axios');
2. (可选但推荐)将抛出内容改为Error实例
JavaScript错误处理的最佳实践是抛出Error对象而非字符串,同时Jest的toThrow对Error实例的匹配更稳定。修改fetchRate的catch块:
export const fetchRate = async (symbol = "BTC") => { try { const response = await axios.get( `https://rest.coinapi.io/v1/exchangerate/${symbol}/USD`, headers ); return response; } catch (e) { // 改为抛出Error实例 throw new Error(e.response.data.error); } };
3. 贴合测试场景传入无效symbol
虽然当前Mock会让所有请求拒绝,但传入明确的无效symbol能让测试逻辑更清晰:
test("If incorrect symbol is passed the function throws an error", async () => { const e = { response: { data: { error: "We didn't find your currency", }, status: 550, }, }; axios.get.mockRejectedValueOnce(e); // 传入无效symbol而非默认的BTC await expect(fetchRate('INVALID')).rejects.toThrow("We didn't find your currency"); });
完整测试文件示例
import axios from 'axios'; import { fetchRate } from './your-file-path'; // Mock axios模块 jest.mock('axios'); test("If incorrect symbol is passed the function throws an error", async () => { const mockError = { response: { data: { error: "We didn't find your currency", }, status: 550, }, }; axios.get.mockRejectedValueOnce(mockError); await expect(fetchRate('INVALID')).rejects.toThrow("We didn't find your currency"); });
额外检查:确认headers变量在fetchRate函数中已正确引入,避免因其他变量缺失导致非预期的请求失败。
内容的提问来源于stack exchange,提问作者SrdjaNo1
相关产品推荐
相关产品推荐

