3

我正在尝试在 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");
    }
  });
});
4

1 回答 1

2

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

Angular 7 测试 retryWhen 使用模拟 http 请求无法实际重试

正在添加的关键部分:

  1. 每次刷新后滴答(2500)
  2. 制作测试 fakeAsync (这样你就可以使用滴答声)。

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

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();
});
于 2020-01-14T00:20:46.557 回答