如何使用 Jasmine 在 Angular 中对 HTTP 拦截器进行单元测试

knb*_*bin 6 unit-testing jasmine angular-http-interceptors angular

我的角度应用程序中有以下 http 拦截器,我想使用 Jasmine 对其进行单元测试。我用谷歌搜索了其中一些并尝试过,但它没有按预期工作。请找到下面的HttpInterceptorService.ts文件代码

export class HttpInterceptorService Implements HttpInterceptor {
 counter = 0;
 constructor(private loaderService: LoaderService) { }
 intercept(req: HttpRequest<any>, next: HttpHandler) {
  if (req.url !== '/getUsers') {
   this.counter ++;
  }
  this.loaderService.setStatus(true);
  return next.handle(req).pipe(
   finalize(() => {
    if (req.url !== 'getUsers') {
      this.counter --;
    }
    if (this.counter === 0) {
      this.loaderService.setStatus(false);
    }
   };
  );
 }
}
Run Code Online (Sandbox Code Playgroud)

以下是我目前尝试过的 HttpInterceptor.service.spec.ts 文件代码。我不确定如何测试其中的特定方法。

describe('HttpInterceptorService', () => {
  let httpService: HttpService;
  let httpMock: HttpTestingController;
  let interceptor: HttpInterceptorService;

  beforeEach(()=> {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
       HttpService,
       {provide:HTTP_INTERCEPTOR, useClass: HttpInterceptorService, multi: true},
      ]
    });
    httpService = TestBed.get(HttpService);
    httpMock = TestBed.get(HttpTestingController);
    interceptor = TestBed.get(HttpInterceptorService);
  });

   it('should increment the counter for all api's expect getUsers', ()=> {
      httpService.get('getAdminList').subscribe(res => {
        expect(res).toBeTruthy();
        expect(interceptor.counter).toBeGreaterThan(0);
      });
   });

   
});
Run Code Online (Sandbox Code Playgroud)

检查参考代码后,我可以用上述更改覆盖几行代码。但我仍然无法涵盖 Finalize 方法。请求好心人帮忙。

knb*_*bin 8

下面的代码有助于覆盖 Finalize 运算符内的代码。

const next: any = {
  handle: () => {
    return Observable.create(subscriber => {
      subscriber.complete();
    });
  }
};

const requestMock = new HttpRequest('GET', '/test');

interceptor.intercept(requestMock, next).subscribe(() => {
  expect(interceptor.counter).toBeGreaterThan(0);
});
Run Code Online (Sandbox Code Playgroud)

  • 我知道这个问题已经有点老了,但应该提到的是,在这个答案中(至少在 Angular 12 中)测试将通过误报。处理程序完成时不会发出 subscribe 方法捕获的值。要捕获完整事件,需要使用 .subscribe({complete: () =&gt; ...}) (2认同)