如何在业力单元测试中模拟Angular HttpClient帖子调用?

时间:2018-06-29 14:11:18

标签: angular karma-jasmine angular-http angular-http-interceptors angular-httpclient

我的组件的query()函数中包含以下代码,并且我想模拟http post返回的结果,该怎么办?

query(){
    Observable.forkJoin(
      this.http.post<any[]>(URL, jsonBody1, postJson) .map((res) => res),
      this.http.post<any[]>(URL, jsonBody2, postJson) .map((res) => res)
    )
    .subscribe(res => this.handleResponse(res))
}

1 个答案:

答案 0 :(得分:1)

Angular TestBed中提供了一个模拟功能,您可以使用它。

确保将HttpModule导入测试床,然后模拟http服务。

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        FormsModule,
        HttpModule
      ],
      declarations: [
      ],
      providers: [
      ]
    })
      .compileComponents();
  }));

然后从设备调用您的服务。

xxx = fixture.debugElement.injector.get(someService);

然后在您进行测试时,您可以窥探并说出期望得到的回报。

const error = spyOn(someService, 'someMethod').and.returnValue(
  Observable.throw({error: 'this is a error'})
);