GPD21352
GPD21352

Reputation: 59

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?

Upvotes: 0

Views: 2370

Answers (2)

Sandeep
Sandeep

Reputation: 569

I have implemented is as follows 1. Define one variable in service which indicates mock response like isMockResponse = true. 2. I created one config file which has a mapping of URL vs response JSON file. like this

{ POST : { "/login": { responseFile: loginResponse.json}}}

I kept responseFile under asset folder and making sure that the response file folder should be excluded on a production build. (you can define it in angular.json file) 3. create loginResponse.json file inside assets/offline/response/loginResponse.json location 4. in the interceptor, I am checking the flag isMockResponse and if it's true then redirect request to get a file from the assets folder instead of going to the server.

 let rspFile = "/assets/offline/response/" + extn + ".json";
  Utility.log("rspFile " + rspFile);
  const dupReq = request.clone({ url: rspFile, method: "get" });
  return next.handle(dupReq);

Where extn is the "loginResponse" which I am getting from configuration file. This way, you don't need to customise code.In case of isMockresponse= false you simply forward request to server like this

return next.handle(request);

Upvotes: 0

MichaelKie
MichaelKie

Reputation: 146

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!

Upvotes: 1

Related Questions