How to mock HTTP Request in Angular?

时间秒杀一切 提交于 2021-01-29 10:39:17

问题


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 ?


回答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');



回答2:


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




回答3:


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




回答4:


JSON-Server : https://www.npmjs.com/package/json-server

It will give you a mock server with all(GET, POST, PUT, DELETE etc) rest APIs from the .json file...




回答5:


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.




回答6:


You can put the response json in the asset folder and do the testing.

For example create a test.json file under assets/json and change your url accordingly

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

You can also configure the url to be selected based on the environment variable so that in the prod build actual url will be taken and in dev the dummy one.



来源:https://stackoverflow.com/questions/58950805/how-to-mock-http-request-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!