如何在Angular中模拟HTTP请求? [英] How to mock HTTP Request in Angular?

查看:74
本文介绍了如何在Angular中模拟HTTP请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了很多文章和答案,但似乎找不到为我的方法模拟HTTP Requests的正确方法.我想独立于backend测试我的frontend应用程序.这是我使用的方法的类型:

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();
      });
  }

有什么建议吗?

推荐答案

通常,我使用HttpClientTestingModule模拟我的Http请求:

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

这篇关于如何在Angular中模拟HTTP请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆