首页 > 解决方案 > 如何在单元测试 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

有没有人遇到过这个用例?

标签: unit-testingtestingnestjs

解决方案


德回答有效,但如果你想要一些更漂亮的方式,你可能会喜欢这个,

 it('should return null when update', async () => {

  await expect(controller.updateById({ id: 'some id' }, {}))
  .rejects.toThrowError(NotFoundException);

});

推荐阅读