简体   繁体   中英

How to write Test Case for Interceptor in Angular

I am trying to test the HttpInterceptor provided by the Angular 6. I have created an interceptor as per the examples but i am unable to write test case for below interceptor please guide me to complete below problem

Interceptor

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

Test

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

Error

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>)

you're test ist right, because you are not calling a service which makes the http-call before your expects.

You can also extend your test with a direct http-call and it should turn green.

...
  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();
  }));
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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