Unit testing HttpInterceptor from Angular 4

后端 未结 5 1755
情书的邮戳
情书的邮戳 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:38

    Just make any call and mock the response with .error() method of HttpTestingController and it should work.

    describe('Error interceptor', function () {
    let http: HttpTestingController;
      let httpClient: HttpClient;
    
      beforeEach(() => {
        const testBed = TestBed.configureTestingModule({
          imports: [HttpClientTestingModule],
          providers: [
            {
              provide: HTTP_INTERCEPTORS,
              useClass: MyInterceptor,
              multi: true
            }
          ],
        });
    
     http = testBed.get(HttpTestingController);
     httpClient = testBed.get(HttpClient);
     });
    
      it('should catch 401', function (done) {
        httpClient.get('/error').subscribe(() => {}, () => {
          // Perform test
          done();
        });
    
        http.expectOne('/error').error(new ErrorEvent('Unauthorized error'), {
          status: 401
        });
        http.verify();
      });
    
    });
    

提交回复
热议问题