How to mock HTTP Request in Angular?

20,100

Solution 1

Usually i mock my Http requests with HttpClientTestingModule :

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

export class TestService {
    constructor(private http: HttpClient) {}
}

describe('AppInterceptor', () => {
    let service: TestService;
    let httpMock: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [
                TestService
            ]
        });
        service = TestBed.get(TestService);
        httpMock = TestBed.get(HttpTestingController);
    });

....
const httpRequest = httpMock.expectOne('any-url');

Solution 2

in order to fake the backend server response, you need to create a service that implements the HttpInterceptor interface

https://medium.com/@lanoTechno/intro-to-angular-http-interceptors-and-how-to-create-backendless-app-with-them-3593f6552b3a

Solution 3

If I understand your question correctly, you want to create your frontend services before your backend, but you still want to use promises / observables. You can use of for that:

import { of } from 'rxjs';
//emits any number of provided values in sequence
const source = of(1, 2, 3, 4, 5);
//output: 1,2,3,4,5
const subscribe = source.subscribe(val => console.log(val));

from https://www.learnrxjs.io/operators/creation/of.html

Solution 4

You can always create a mock method by your own and mock the response that you expect from the backend. In your example it could be

 public static mockGetProfile(){
    const response = JSON.parse(`
     "name": "abc",
     "active": true,
     ...all other json fields that you want
     `);

    let obs = new Observable((subscriber) => {
        setTimeout(()=>{
            subscriber.next(response);
            subscriber.complete();
        }, 3000);
    });
    return obs;
}

The above observable will complete after 3 seconds or what ever period you define, simulating in a way the response from a backend server which will need some time to be available.

Share:
20,100
Basilius Mourk
Author by

Basilius Mourk

Updated on December 08, 2020

Comments

  • Basilius Mourk
    Basilius Mourk over 3 years

    I have checked a lot of articles and answers but I don't seem to find the right way to mock HTTP Requests for my methods. I want to test my frontend application independently from the backend. Here is the type of methods I have:

     private getProfile() {
        this.http
          .get('go/profile/get', {withCredentials: true})
          .subscribe((profile: Profile) => {
            this.user.profile = profile;
            this.updateLineMsgs();
          });
      }
    

    Any suggestions ?