gpt4 book ai didi

unit-testing - 如何在单元测试 Nest.js 中测试抛出新的 HttpException

转载 作者:行者123 更新时间:2023-12-03 16:37:18 28 4
gpt4 key购买 nike

我正在尝试在我的 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 (done) => {
jest.spyOn(service, 'updateById').mockResolvedValue(null)

try {
await controller.updateById({ id: 'some id' }, {})
} catch (error) {
expect(error).toBeInstanceOf(NotFoundException)
done()
}
})

关于unit-testing - 如何在单元测试 Nest.js 中测试抛出新的 HttpException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60118380/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com