【发布时间】:2020-05-23 21:09:06
【问题描述】:
我正在尝试在我的 Nest.js 应用中测试服务。在此服务的某些方法中,我会根据上下文抛出新的 HttpException。
我正在尝试编写这些方法的单元测试,但我不知道如何测试我抛出 HttpException 的用例。
我试过这段代码:
it('Shound return error for a non existing id provided', async () => {
await expect(service.getUser('false Id')).rejects.toThrow(new HttpException('This user does not exist', 404));
});
但我收到了:
Expected the function to throw an error matching:
[Error: This user does not exist]
Instead, it threw:
Error: This user does not exist
有人遇到过这个用例吗?
【问题讨论】:
-
你在
service.getUser()中抛出了什么错误?NotFoundException还是HttpException?请注意,您也可以仅使用toThrow('This user ...')测试错误消息 -
我在 service.getUser() 中抛出了 HttpException。我尝试过这样的测试:
await expect(service.getUser('false Id')).toThrow('This user does not exist');或类似的测试:await expect(service.getUser('false Id')).rejects.toThrow('This user does not exist');但这些解决方案似乎都不起作用。 -
我终于决定不在单元测试中而是在端到端测试中测试 throw HttpException
标签: unit-testing testing nestjs