如何解决在 Jest 测试中断言自定义错误消息?
在测试中使用 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']
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。