如何在可观察的情况下测试例外?
我有一个可观察到的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在使用
可观察到
时,您需要了解,您不能依靠async/等待
来考虑完成测试。因此,您可以使用完成
参数为您处理。在您的示例中,您需要在
get
函数的模拟实现中返回可观察的
,并且在该可观察到的
中,您应该丢下错误。While working with
Observables
you need to understand that you can't rely onasync/await
to consider your test done. So, you can use thedone
parameter to handle that for you.In your example, you will need to return an
Observable
within the mock implementation of theget
function and, within thatObservable
you should throw an error.