【问题标题】:How to mock Angular HttpClient post call in karma unit test?如何在业力单元测试中模拟 Angular HttpClient 后调用?
【发布时间】:2026-02-20 09:10:01
【问题描述】:

我的组件的 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))
}

【问题讨论】:

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


    【解决方案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'})
    );
    

    【讨论】:

    • 如果我返回一个值而不是错误,returnValue 会是什么样子?
    • 你可以直接说Observable.of({something: 'somevalue'}),它会来到.subscribe块而不是.error
    最近更新 更多