Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock HTTP Request in Angular?

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 ?

like image 620
Basilius Mourk Avatar asked Jan 26 '23 14:01

Basilius Mourk


2 Answers

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.inject(TestService);
        httpMock = TestBed.inject(HttpTestingController);
    });

//...
const httpRequest = httpMock.expectOne('any-url');
like image 41
Benjamin Barbé Avatar answered Jan 28 '23 05:01

Benjamin Barbé


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.

like image 198
Panagiotis Bougioukos Avatar answered Jan 28 '23 04:01

Panagiotis Bougioukos