角度单元测试-在HttpInterceptor中

时间:2019-11-21 09:58:12

标签: angular unit-testing retrywhen httptestingcontroller

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

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

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

我的拦截器工作正常,并且正在使用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");
    }
  });
});

1 个答案:

答案 0 :(得分:2)

我只是遇到了完全相同的问题,并且在阅读了该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();
});