问题描述
在测试中使用 got
库时是否可以对自定义错误消息进行断言?如果响应 >= 400,Got
将抛出错误,因此我可以对响应代码进行断言(通过字符串得到返回),但不能断言我自己的自定义错误消息。
it('Responds with a 404 if not found',async () => {
const paramA = 'a param that will make my function fail';
try {
await got(
`http://localhost:${port}/myEndpointName/${paramA}`,);
} catch (error) {
// Would Like to assert on this statement below
// expect(error.message).toEqual("A custom error message of my selection");
// But instead I have to assert on this
expect(error.message).toEqual("Response code 404 (Not Found)");
}
});
export const doStuff: RequestHandler = async function (req,res,next) {
const { paramA } = req.params;
try {
const stuffFromElsewhere: NPMPackage = await got(
`https://someothersite.com/${paramA}`,).json();
return res.status(200).json({ paramA,"good job" });
} catch (error) {
return res.status(404).json({ message: 'A custom error message of my selection' });
}
};
解决方法
您的错误是常见的 http 错误,它是由 got
而非您的服务器逻辑引发的。
如果你想断言响应错误信息,让我们试试:
expect(error.response.body.message).toEqual("A custom error message of my selection");
,
答案是在 JSON.parse(resError.response.body)['message']