加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在Angular中创建一个模拟observable来测试http rxjs重试/重

发布时间:2020-12-17 17:11:34 所属栏目:安全 来源:网络整理
导读:我在我的角度应用程序中有这个表单的http请求:this.http.get(url,options).pipe(retry(5)) 我想使用jasmine对此进行单元测试,以便http请求首先返回错误,但在随后的尝试中,返回预期的数据. 我之前按照angular.io文档spyOn(http,’get’)和.returnValue(defer
我在我的角度应用程序中有这个表单的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 --#");
  });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读