我在我的角度应用程序中有这个表单的http请求:this.http.get(url,options).pipe(retry(5))
我想使用jasmine对此进行单元测试,以便http请求首先返回错误,但在随后的尝试中,返回预期的数据.
我之前按照angular.io文档spyOn(http,’get’)和.returnValue(defer(()=> Promise.reject(errorObject)))的建议,以这种格式返回了http错误.
rxjs运算符重试似乎没有再次调用http.get函数,因此更改spy的返回值不起作用.我认为我需要做的是以某种方式从间谍返回一个observable,它首先发出错误然后发出数据.我想过使用BehaviorSubject但不认为接受错误传递.
有没有办法实现这个目标?
解决方法
如果我们转到角度
source code,我们将看到下一个:
// 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 --#"); });