use*_*045 6 testing unit-testing nestjs
我正在尝试在我的 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));
});
Run Code Online (Sandbox Code Playgroud)
但我收到了:
Expected the function to throw an error matching:
[Error: This user does not exist]
Instead, it threw:
Error: This user does not exist
Run Code Online (Sandbox Code Playgroud)
有没有人遇到过这个用例?
M.a*_*man 27
Duc 的答案有效,但如果你想要一些更漂亮的方式,你可能会喜欢这个,
it('should return null when update', async () => {
await expect(controller.updateById({ id: 'some id' }, {}))
.rejects.toThrowError(NotFoundException);
});
Run Code Online (Sandbox Code Playgroud)
只需这样做:
it('should return null when update', async (done) => {
jest.spyOn(service, 'updateById').mockResolvedValue(null)
try {
await controller.updateById({ id: 'some id' }, {})
} catch (error) {
expect(error).toBeInstanceOf(NotFoundException)
done()
}
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2257 次 |
| 最近记录: |