【问题标题】:Angular unit test - testing retryWhen in HttpInterceptorAngular 单元测试 - 在 HttpInterceptor 中测试 retryWhen
【发布时间】:2019-11-21 09:58:12
【问题描述】:

我正在尝试在 http 拦截器中测试 retryWhen 运算符,但在尝试多次重复我的服务调用时出现错误:

“错误:预期有一个针对条件“匹配 URL:http://someurl/tesdata”的匹配请求,但没有找到。”

所以我有两个问题。首先,我是否要以正确的方式进行测试,其次,为什么我不能在没有匹配错误的情况下发出多个服务请求?

我的拦截器工作正常,并且正在使用 rxjs retryWhen 运算符,例如:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
        retryWhen(errors => errors
            .pipe(
            concatMap((err:HttpErrorResponse, count) => iif(
            () => (count < 3),
            of(err).pipe(
                delay((2 + Math.random()) ** count * 200)),
                throwError(err)
            ))
        ))
    );
  }
}

我的测试服务:

import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class InterceptorTestService {

  constructor(private httpClient: HttpClient) { }

  getSomeData() : Observable<boolean>{
    return this.httpClient
      .get('http://someurl/tesdata').pipe(
        map(()=>{
          return true;
        })
      )
  }
}

我的规格:


import { InterceptorTestService } from './interceptor-test.service';
import { HttpClientTestingModule, HttpTestingController, TestRequest } from '@angular/common/http/testing';

describe('InterceptorTestService', () => {

  let service: InterceptorTestService;
  let backend: HttpTestingController;


  beforeEach(() => TestBed.configureTestingModule({
    providers: [InterceptorTestService],
    imports: [HttpClientTestingModule]
  }));

  beforeEach(() =>{
    service = TestBed.get(InterceptorTestService),
    backend = TestBed.get(HttpTestingController)
  });

  it('should be created', () => {
    service.getSomeData().subscribe();


    const retryCount = 3;
    for (var i = 0, c = retryCount + 1; i < c; i++) {
      let req = backend.expectOne('http://someurl/tesdata');
      req.flush("ok");
    }
  });
});

【问题讨论】:

    标签: angular unit-testing retrywhen httptestingcontroller


    【解决方案1】:

    我刚刚遇到了完全相同的问题,并且在阅读了这个 SO 答案并根据我的需要进行调整后解决了:

    Angular 7 testing retryWhen with mock http requests fails to actually retry

    正在添加的关键部分:

    1. 每次刷新后勾选(2500)
    2. 制作测试 fakeAsync(以便您可以使用 tick)。

    这就是我的测试现在的样子以供参考,以防万一它可以帮助你到达你要去的地方(很抱歉没有完全适应你的需要):

    it("addLicensedApplication() should return an error command result if an error occurs", fakeAsync(() => {
      let errResponse: any;
      const mockErrorResponse = { status: 400, statusText: "Bad Request" };
    
      service
        .addLicensedApplication(aCompanyId, LicensedApplicationFlag.workshopPro)
        .subscribe(res => res, err => errResponse = err);
    
      const retryCount = 5;
      for (let i = 0, c = retryCount + 1; i < c; i += 1) {
        const req = httpMock
          .expectOne(`${env.apiProtocol}${env.apiUrl}${Constants.addLicensedApplicationUrl}`);
    
        req.flush(CommandResultErrorFixture, mockErrorResponse);
        tick(2500);
      }
    
      expect(errResponse.error).toBe(CommandResultErrorFixture);
    }));
    
    afterEach(() => {
      httpMock.verify();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-13
      相关资源
      最近更新 更多