Модульное тестирование HttpInterceptor от Angular - PullRequest
0 голосов
/ 04 февраля 2020

Может кто-нибудь сказать мне, как проверить Http-перехватчик, предоставляемый Angular. Я создал перехватчик согласно моим знаниям, но не уверен, как это проверить. Ниже мой перехватчик, и я написал ниже контрольный пример для Перехватчика, но получаю исключение

Может кто-нибудь предложить мне, пожалуйста.

Перехватчик

@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', () => {
    beforeEach(() => TestBed.configureTestingModule({
        imports: [HttpClientTestingModule],
        providers: [{
            provide: HTTP_INTERCEPTORS,
            useClass: AutherizationInterceptor,
            multi: true
        }]
    }));

    it('adds Authorization header', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {
        http.post(`${environment.baseUrl}api/potential/search`,null).subscribe(
            response => {
                expect(response).toBeTruthy();
            }
        );
        const req = httpMock.expectOne(r =>
            r.headers.has('Authorization'));
        expect(req.request.method).toEqual('POST');
        const headers = new HttpHeaders().set(InterceptorSkipHeader, '')
        req.flush(headers);
        httpMock.verify();
    }));
});

Исключение

Lang-interceptor.service adds Authorization header
TypeError: Cannot read property 'length' of null
TypeError: Cannot read property 'length' of null
    at HttpHeaders.push../node_modules/@angular/common/fesm5/http.js.HttpHeaders.applyUpdate (http://localhost:9876/_karma_webpack_/webpack:/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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...