【问题标题】:Not getting coverage when testing async function that throws error测试引发错误的异步函数时未获得覆盖
【发布时间】:2021-11-27 02:42:21
【问题描述】:

我正在尝试为以下方法编写单元测试,以检查它是否会引发 NotFoundException 类型的错误。测试按预期通过,但我无法覆盖 catchError 块中的行。第 13 和 14 行。

我想知道我在这里缺少什么?

正在测试的方法:

  async updateContact(
    contactId: number,
    authToken: string,
    data: Record<string, any>,
  ): Promise<Record<string, unknown>> {
    return this.httpService
      .put(`${this.config.customer.url}/contacts/${contactId}`, data, {
        headers: { Authorization: authToken },
      })
      .pipe(
        pluck('data'),
        catchError(err => {
          console.dir(err);
          throw err;
        }),
      )
      .toPromise();
  }

我的测试:

 const contactId = 1;
    const authToken = 'Bearer f4k3-70k3n';
    const data = { policy_id: 2 };

    it('should throw NotFoundException', async () => {
      jest.spyOn(sessionService, 'updateContact').mockRejectedValueOnce(new NotFoundException());
      await expect(sessionService.updateContact(contactId, authToken, data)).rejects.toThrowError(NotFoundException);
    });

【问题讨论】:

    标签: unit-testing jestjs nestjs


    【解决方案1】:

    我意识到了错误......

    我写了一个测试,导致 updateContact 方法失败,这就是测试通过的原因。但是 catch 块连接到 httpService.put 方法,因此为了能够到达 catchError 块中的行,我需要使该方法失败。

    it('should throw http exception', async () => {
          jest.spyOn(httpService, 'put').mockReturnValueOnce(throwError(new NotFoundException()));
          await expect(sessionService.updateContact(contactId, authToken, data)).rejects.toThrowError(NotFoundException);
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多