2017-09-14 33 views
6

角度4で提供されているHttpInterceptorのテスト方法を教えてもらえますか?例に応じてインターセプターを作成しましたが、テスト方法は不明です。以下は私のインターセプターで、カスタムヘッダーが追加されているかどうか、そして応答ステータスが401の場合にテストしたいと思います。window.location.hrefが完了しました。ユニットテストHttpInterceptor from 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); 
      }); 
    } 

答えて

0

インターセプタテストはAngularサービスのテストに似ています。そして、TestBedはそれらをテストするために必要なものすべてを提供するつもりです。

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

あなたのサービスを嘲笑すると、テスト中に複製したいデータが得られます。

+0

ありがとうございますが、私はこの場合yourMockが何であるか分かりません。 http.getを呼び出して、インターセプタがヘッダーを追加したかどうかと、レスポンスを疑似したいかどうかを確認したいと思います。 – Angad

+0

をスキップすることができます。あなたが何かを嘲笑していない場合は必要ありません。 –

10

私は同じようなことをテスト捕まってしまったが、アリサの記事Intercepting Http Requestsのおかげで、私はそれだけですべての呼び出しを行うとHttpTestingController.error()方法で応答を模擬し、それが動作するはず

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

を動作するようになりました。

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

私は少し遅れてポストへんだけど、私は角のコンテキストのインターセプタ外をテストする方法を考え出しました。つまり、HTTPコールをモックする必要はなく、任意のJavascript関数のようにintercept関数をテストするだけです。

のは、あなたのインターセプタが唯一のエラーステータスが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'); } 
    }); 
} 

それと

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

、あなたのインターセプタのためのテストを書くことができます。

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

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

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

出来上がり!