2017-09-14 15 views
6

Bạn có thể cho tôi biết làm thế nào để kiểm tra HttpInterceptor được cung cấp bởi Angular 4. Tôi đã tạo ra một interceptor theo các ví dụ nhưng không chắc chắn làm thế nào để kiểm tra nó. Dưới đây là đánh chặn của tôi và tôi muốn kiểm tra nếu các tiêu đề tùy chỉnh được thêm vào và khi trạng thái phản hồi là 401 window.location.href được thực hiện.Kiểm thử đơn vị HttpInterceptor từ Angular 4

export class MyInterceptor implements HttpInterceptor { 

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
     const headers = new HttpHeaders(); 
     this.addHeader(headers); // This will add headers 

     const changedReq = req.clone({ headers: headers }); 
     return next.handle(req) 
      .catch(err => { 
       if (err instanceof HttpErrorResponse) { 
        switch (err.status) { 
         case 302: 
         case 401: 
          window.location.href = "http//google.com"; 
          break;    
         default: 
          throw new Error(this.getErrorMessage(err)); 
        } 
       } 

       return Observable.throw(err); 
      }); 
    } 

Trả lời

0

Kiểm tra đánh chặn tương tự như Kiểm tra dịch vụ góc. Và TestBed sẽ cung cấp tất cả những gì bạn cần để kiểm tra chúng.

beforeEach(() => { 
     TestBed.configureTestingModule({ 
      imports: [HttpClientTestingModule], 
      providers: [ 
       { 
        provide: HTTP_INTERCEPTORS, 
        useClass: MyInterceptor, 
        multi: true 
       }] 
     }); 
    }); 


describe('making http calls',() => { 
     it('adding header test', inject([HttpClient, YourMock], (http: HttpClient, httpMock: YourMock) => { 

      http.get('/data').subscribe(
       response => { 
        expect(response).toBeTruthy(); 
       } 
      ); 

      expect(response.status).toEqual('401'); 
     })); 
    }); 

Mocking dịch vụ sẽ cung cấp cho bạn dữ liệu mà bạn muốn sao chép trong khi kiểm tra.

+0

Cảm ơn nhưng tôi không hiểu yourMock là gì trong trường hợp này. Tôi muốn thực hiện cuộc gọi http.get và muốn kiểm tra xem máy đánh chặn đã thêm các tiêu đề và muốn giả lập phản hồi hay không. – Angad

+0

bạn có thể bỏ qua điều đó. nó không cần thiết nếu bạn không chế giễu bất cứ điều gì. –

10

tôi đã bị mắc kẹt thử nghiệm một điều tương tự, nhưng nhờ bài viết của Alisa Intercepting Http Requests tôi đã nhận nó làm việc

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

Chỉ cần thực hiện bất kỳ cuộc gọi và thử phản ứng với .error() phương pháp HttpTestingController và nó sẽ làm việc.

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

}); 
1

Tôi hơi muộn đến bưu điện, nhưng tôi đã tìm ra một cách để thử nghiệm các tên lửa đánh chặn ngoài bối cảnh góc của. Điều này có nghĩa là bạn không phải giả lập các cuộc gọi HTTP, bạn chỉ kiểm tra chức năng intercept như bất kỳ chức năng Javascript nào.

Hãy nói rằng đánh chặn của bạn chỉ làm điều đó, mà đang hiển thị một bản ghi nếu tình trạng lỗi là 500:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
    return next 
    .handle(req) 
    .catch((err: HttpErrorResponse) => { 
     if(err.status === 500) { console.log('Server error'); } 
    }); 
} 

Sau đó, trong dịch vụ của bạn, bạn có thể thử các thông số của chức năng của bạn như sau:

const err: any = { status: 500 }; 
const next: any = { 
    handle: (request: HttpRequest<any>) => ({ 
    catch: (callback: Function) => callback(err) 
    }) 
}; 

với điều đó, bạn có thể viết một bài kiểm tra cho đánh chặn của bạn:

it('should write a console log with error status equal to 500',() => { 
    spyOn(console, 'log'); 

    service.intercept({} as any, next); 

    expect(console.log).toHaveBeenCalled(); 
}); 

và voila !

Các vấn đề liên quan