如何在可观察的情况下测试例外?

发布于 2025-02-11 10:13:58 字数 863 浏览 1 评论 0原文

我有一个可观察到的httpservice,但是就在返回之前,我将其变成了“ lastvalue”的诺言,

 async getRandomRecipes(): Promise<BasicRecipe> {
    const res = this.httpService
      .get<ClientBasicRecipe>(url)
      .pipe(
        map((response) => {
          return response.data;
        }),
        catchError((err) => throwError(() => new NotFoundException())), // Trying to test this exception
      )
      .pipe<BasicRecipe>(map((data) => this.getBasicRecipe(data)));

    return lastValueFrom(res);
  }

我想用嘲笑测试这个例外,但不确定该怎么做。我知道在httpservice上使用jest.spyon,但由于它是可观察的。我不知道如何正确嘲笑它。

这就是我到目前为止的:

   it("throw NotFoundException when there are no recipes", async ()=>{
      jest
      .spyOn(HttpService.prototype, 'get')
      .mockImplementationOnce(() => throw new NotFoundException);
    })

I have httpService that is an Observable, but just before returning, I'm turning it into a Promise with "lastValueFrom"

 async getRandomRecipes(): Promise<BasicRecipe> {
    const res = this.httpService
      .get<ClientBasicRecipe>(url)
      .pipe(
        map((response) => {
          return response.data;
        }),
        catchError((err) => throwError(() => new NotFoundException())), // Trying to test this exception
      )
      .pipe<BasicRecipe>(map((data) => this.getBasicRecipe(data)));

    return lastValueFrom(res);
  }

I want to test this exception with jest, but not sure how to do it. I know to use jest.spyOn on HttpService, but since it's an Observable; I don't know how to mock it properly.

This is what I have so far:

   it("throw NotFoundException when there are no recipes", async ()=>{
      jest
      .spyOn(HttpService.prototype, 'get')
      .mockImplementationOnce(() => throw new NotFoundException);
    })

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青柠芒果 2025-02-18 10:13:59

在使用可观察到时,您需要了解,您不能依靠async/等待来考虑完成测试。因此,您可以使用完成参数为您处理。

在您的示例中,您需要在get函数的模拟实现中返回可观察的,并且在该可观察到的中,您应该丢下错误。

While working with Observables you need to understand that you can't rely on async/await to consider your test done. So, you can use the done parameter to handle that for you.

In your example, you will need to return an Observable within the mock implementation of the get function and, within that Observable you should throw an error.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文