如何在 Angular 中模拟 HTTP 请求?

Bas*_*urk 12 unit-testing jasmine karma-jasmine angular angular-test

我检查了很多文章和答案,但我似乎没有找到模拟HTTP Requests我的方法的正确方法。我想frontend独立于backend. 这是我拥有的方法类型:

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

有什么建议 ?

Ben*_*rbé 9

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

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');
Run Code Online (Sandbox Code Playgroud)


Pan*_*kos 9

您始终可以自己创建一个模拟方法并模拟您期望从后端获得的响应。在你的例子中它可能是

 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;
}
Run Code Online (Sandbox Code Playgroud)

上面的可观察结果将在 3 秒或您定义的任何时间段后完成,以某种方式模拟后端服务器的响应,这需要一些时间才能可用。


Vik*_*iya -3

您可以将响应 json 放在 asset 文件夹中并进行测试。

例如,在 assets/json 下创建一个 test.json 文件并相应地更改您的 url

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

您还可以根据环境变量配置要选择的 url,以便在 prod 构建中采用实际 url,而在 dev 中采用虚拟 url。