角度单元测试 - 在 HttpInterceptor 中测试重试



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

"错误:预期对条件"匹配 URL: http://someurl/tesdata"的一个匹配请求,未找到任何请求。

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

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

  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");
    }
  });
});

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

Angular 7 测试重试当模拟 http 请求实际重试失败时

添加的关键部分是:

  1. 每次刷新后滴答(2500(
  2. 使测试假异步(这样你就可以使用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();
});

相关内容

  • 没有找到相关文章

最新更新