是否存在另一种方法如何在将 JS/TS 与 Axios 和 Jest 库一起使用时处理错误消息,以便获取请求失败的更多信息?
例如:
const req = await callApi(payload)
expect(req.status).toEqual(200)
假设上面的检查在状态 400 时失败 使用上面的代码您只收到
Request failed with status code 400
并且没有验证失败的信息。
我了解 try/catch - 但有些事情告诉我,在自动化测试中使用 try/catch 不是一个好主意。也许我错了。此外,如果你使用 try/catch,你也必须在 catch 块中期望状态 200,因为如果你不在那里使用期望,测试将面临成功,尽管事实上发生了错误。
另一种方法是使用 Promise - then - 构造。实际上,try/catch 更糟糕:) 你知道,有很多不必要且复杂的代码。
那么,是否有可能以某种方式扩展 Axios 或 Jest 中的错误处理程序/函数以接收信息?
首先,您需要捕获
callApi
中的错误
例如
async function callApi(payload) {
try {
const response = await axios.post('/api-url', payload);
return response;
} catch (error) {
if (error.response) {
throw new Error(`Failed with status ${error.response.status}: ${error.response.data.detail}`);
} else {
throw error;
}
}
}
然后在
Jest
中,您可以使用resolves
和rejects
来处理成功和失败。
test('API succeed with status 200', () => {
return expect(callApi(payload)).resolves.toHaveProperty('status', 200);
});
test('API fail with status 400 and detailed error', () => {
return expect(callApi(payload)).rejects.toThrow('Validation details');
});