unit-testing - 如何在单元测试 Nest.js 中测试抛出新的 HttpException
问题描述
我正在尝试在我的 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
有没有人遇到过这个用例?
解决方案
德回答有效,但如果你想要一些更漂亮的方式,你可能会喜欢这个,
it('should return null when update', async () => {
await expect(controller.updateById({ id: 'some id' }, {}))
.rejects.toThrowError(NotFoundException);
});
推荐阅读
- asp.net - 将 global.asax 更改为 owin 启动以使用 signalR 2
- reactjs - React/Redux/Firebase 延迟加载
- sql - 仅使用具有“in”子句中所有值的列加入查询
- jupyter-lab - 如何为 Jupyter 实验室创建自定义 css 文件
- python - 无法为张量“Placeholder_24:0”提供形状(25、2、1)的值,其形状为“(?,2)”张量流python
- java - 使用 @RunWith(PowerMockRunner.class) 时出现 NoClassDefFoundError
- rabbitmq - 使用rabbitMQ的任务队列
- php - 使用ajax数据表Codeigniter根据登录会话的数据?
- reactjs - 让 webpack 4 在 index.html 中提供 .css.gz 文件
- django - Django:将手动查询集附加到查询集对象