Search code examples
angularmockinghttprequestkarma-jasmineangular-http-interceptors

Angular 5 - Using HTTP Interceptors as mock HTTP requests in Jasmine / Karma tests


In use case tests written using Jasmine and Karma for components written using Angular, can you use HTTP interceptors as mock HTTP requests and responses? If yes, what's one example of using interceptors?


Solution

  • No need to use HTTPInterceptors, if you only want to use mocked HTTP requests, you can simply use mocked Services. Lets say you have a simple data.service.ts like this:

    import { Injectable } from '@angular/core';
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Observable } from 'rxjs/Observable';
    
    @Injectable()
    export class DataService {
    
        constructor(private http: HttpClient) {
    
        }
    
        getData(): Observable<Data[]> {
          return this.http.get<Data[]>(url);
        }
    }
    

    You can mock your in a file called mockData.service.ts:

    import { Injectable } from '@angular/core';
    import 'rxjs/add/observable/of';
    import { Observable } from 'rxjs/Observable';
    
    @Injectable()
    export class MockDataService {
    // Your data goes either here or import it via an external file
    data: Data[] = [
    ...
    ];
    constructor() {
    
    }
    
    // Use the same name for the method here
    getData(): Observable<Data[]> {
      return Obersvable.of(this.data);
    }
    

    In your test file component.spec.ts you simply use the mocked dataservice like this inside of TestBed.configureTestingModule:

    providers: [
                {
                    provide: DataService,
                    useClass: MockDataService
                }
    ]
    

    Just define all the http methods that get used in the component you're testing and provide the according data.

    Hope this helps!