大佬教程收集整理的这篇文章主要介绍了如何在Angular中创建一个模拟observable来测试http rxjs重试/重试?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用jasmine对此进行单元测试,以便http请求首先返回错误,但在随后的尝试中,返回预期的数据.
我之前按照angular.io文档spyOn(http,’get’)和.returnValue(defer(()=> Promise.reject(errorObject)))的建议,以这种格式返回了http错误.
rxjs运算符重试似乎没有再次调用http.get函数,因此更改spy的返回值不起作用.我认为我需要做的是以某种方式从间谍返回一个observable,它首先发出错误然后发出数据.我想过使用BehaviorSubject但不认为接受错误传递.
有没有办法实现这个目标?
// Start with an Observable.of() the initial request,and run the handler (which // includes all interceptors) inside a concatMap(). This way,the handler runs // inside an Observable chain,which causes interceptors to be re-run on every // subscription (this also makes retries re-run the handler,including interceptors). const events$: Observable<httpEvent<any>> = of (req).pipe(concatMap((req: httprequest<any>) => this.handler.handle(req)));
为了使请求可以重现,他们使用(req)启动它,因此我们可以在单元测试中模拟这种行为.例如:
spyOn(http,"get").and.returnValue( createRetriableStream( throwError("err"),throwError("err"),of("a") ) );
createRetriableStream函数可能看起来像这样:
function createRetriableStream(...resp$: any): any { let fetchData: Spy = createSpy("fetchData"); fetchData.and.returnValues(...resp$); return of(undefined).pipe(switchMap((_) => fetchData())); }
通常,重试逻辑与尝试之间的延迟一起使用,以覆盖此部分,您可以使用time progression syntax.因此您的测试可能如下所示:
it("throw error after 2 retries",() => { testscheduler.run(({ cold,expectObservable }) => { source$= createRetriableStream(cold("-#"),cold("-#"),cold("-3")).pipe( retryWhen( return errors.pipe( mergeMap((err) => { return 2 > repeatCount ? throwError(err) : timer(100,testscheduler); }) );) ); expectObservable(source$).toBe("- 200ms --#"); });
以上是大佬教程为你收集整理的如何在Angular中创建一个模拟observable来测试http rxjs重试/重试?全部内容,希望文章能够帮你解决如何在Angular中创建一个模拟observable来测试http rxjs重试/重试?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。