繁体   English   中英

如何在 Angular 中编写拦截器的测试用例

[英]How to write Test Case for Interceptor in Angular

我正在尝试测试 Angular 6 提供的 HttpInterceptor。我根据示例创建了一个拦截器,但我无法为下面的拦截器编写测试用例,请指导我完成以下问题

拦截器

@Injectable()
export class AutherizationInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (req.headers.has(InterceptorSkipHeader)) {
      const headers = req.headers.delete(InterceptorSkipHeader);
      return next.handle(req.clone({ headers }));
    } else {
      const modified = req.clone({
        setHeaders:
        {
          'Authorization': localStorage.getItem(GlobalVariables.AUTHERIZATION_TOEKN),
          'Content-Type': 'application/json'
        }
      });
      return next.handle(modified);
    }
  }
}

测试

describe('Lang-interceptor.service', () => {

let httpMock: HttpTestingController;
let interceptor: AutherizationInterceptor;
beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [HttpClientModule, HttpClientTestingModule],
        providers: [{
            provide: HTTP_INTERCEPTORS,
            useClass: AutherizationInterceptor,
            multi: true
        }]
    })
    httpMock = TestBed.get(HttpTestingController);
    interceptor = new AutherizationInterceptor();
});

it('should include a Content-Type header', inject([HttpClient], (http: HttpClient) => {
    const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json'})
    }
    http.post(environment.baseUrl + 'api/user/login',null, httpOptions).subscribe();
    const httpRequest = httpMock.expectOne(environment.baseUrl + 'api/user/login');
    httpRequest.request.headers.delete(InterceptorSkipHeader);
    expect(httpRequest.request.headers.has('Content-Type')).toBe(true);
    expect(httpRequest.request.headers.get('Content-Type')).toBe('application/json');

    httpMock.verify();
  }));

错误

Chrome 75.0.3770 (Windows 10.0.0) Lang-interceptor.service should include a Content-Type header FAILED
    TypeError: Cannot read property 'length' of null
        at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.applyUpdate node_modules/@angular/common/fesm5/http.js:200:1)
        at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/common/fesm5/http.js:171:60
        at Array.forEach (<anonymous>)

你的测试是对的,因为你没有调用一个在你期望之前进行 http 调用的服务。

您还可以使用直接 http 调用扩展您的测试,它应该会变成绿色。

...
  it('should include a Content-Type header', inject([HttpClient], (http: HttpClient) => {

    const httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json'})
    }

    http.get(environment.baseUrl + 'api/user/login', httpOptions).subscribe();

    const httpRequest = httpMock.expectOne(environment.baseUrl + 'api/user/login');
     // httpRequest.request.headers.delete(InterceptorSkipHeader);

    expect(httpRequest.request.headers.has('Content-Type')).toBe(true);
    expect(httpRequest.request.headers.get('Content-Type')).toBe('application/json');

    httpMock.verify();
  }));
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM