为何该测试未失败?设置auth_token预期为Number却未触发失败
问题原因及解决办法
核心原因:异常被吞了
你的代码里加了try/catch块,但catch里只打印了错误信息,没有把错误重新抛出来。Jest是靠捕获断言失败抛出的异常来判定测试失败的,现在错误被你“按住”了,Jest根本不知道断言失败了,所以测试就直接通过了。
另外还有个可能:你预期response.data是数组格式,但接口实际返回的是单个对象(比如{auth_token: "xxx"}而不是[{auth_token: "xxx"}]),这时候断言本来也不匹配,但同样因为catch吞了错误,没触发失败。
解决步骤
- 移除多余的try/catch:Jest本身会处理异步测试中的错误,不需要手动捕获,直接写断言就行:
describe('Login customer endpoint', () => { it('should return response code of 200 if the user credentials are correct', async () => { const response = await axiosI.post('customer/login', correctCredentialsPayload); expect(response.status).toBe(200); // 先确认接口实际返回的结构,是数组还是对象 expect(response.data).toEqual({ auth_token: expect.any(Number) }) }) });
- 如果必须保留try/catch,一定要重新抛出错误:
catch (error) { console.log(error.message); throw error; // 把错误抛给Jest,让它判定测试失败 }
- 核对接口返回结构:先打印
response.data看看实际是数组还是单个对象,把断言的结构改成和实际返回一致的。
内容的提问来源于stack exchange,提问作者simon
相关产品推荐
相关产品推荐

