Unit testing HttpInterceptor from Angular 4

后端 未结 5 1756
情书的邮戳
情书的邮戳 2020-12-09 08:57

Can you tell me how to test the HttpInterceptor provided by the Angular 4. I have created an interceptor as per the examples but not sure how to test it. Below is my interce

5条回答
  •  不知归路
    2020-12-09 09:32

    I got stuck testing a similar thing, but thanks to Alisa's article Intercepting HTTP Requests I got it to work

        import {TestBed, inject} from '@angular/core/testing';
        import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';
        import {HTTP_INTERCEPTORS, HttpClient} from '@angular/common/http';
    
        import {LangInterceptorService} from './lang-interceptor.service';
    
        describe('Lang-interceptor.service', () => {
           beforeEach(() => TestBed.configureTestingModule({
                 imports: [HttpClientTestingModule],
                 providers: [{
                             provide: HTTP_INTERCEPTORS,
                             useClass: LangInterceptorService,
                             multi: true
                  }]
           }));
    
           describe('intercept HTTP requests', () => {
                it('should add Accept-Language to Headers', inject([HttpClient, HttpTestingController],
                  (http: HttpClient, mock: HttpTestingController) => {
    
                       http.get('/api').subscribe(response => expect(response).toBeTruthy());
                       const request = mock.expectOne(req => (req.headers.has('Accept-Language') && req.headers.get('Accept-Language') === 'ar'));
    
                       request.flush({data: 'test'});
                       mock.verify();
                 }));
            });
    
            afterEach(inject([HttpTestingController], (mock: HttpTestingController) => {
                 mock.verify();
            }));
        });
    

提交回复
热议问题