【问题标题】:How to test throw new HttpException in unit test Nest.js如何在单元测试 Nest.js 中测试抛出新的 HttpException
【发布时间】: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


【解决方案1】:

只需这样做:

  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()
    }
  })

【讨论】:

    【解决方案2】:

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

     it('should return null when update', async () => {
    
      await expect(controller.updateById({ id: 'some id' }, {}))
      .rejects.toThrowError(NotFoundException);
    
    });
    

    【讨论】:

      猜你喜欢
      • 2021-05-05
      • 1970-01-01
      • 2014-02-28
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 2018-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多