如何在 jasmine 中的 observable 中为 http-post 编写单元测试?

How to write unit-test for http-post inside an observable in jasmine?

我有 web.service.ts,我想为此编写一个单元测试。但是我被困在一种方法中。

updateClientConfiguration(id, data){

   var res = this.http.post<any> 
   (`${this.configUrl}/${this.helper.getNodeIP()}/clients/${id}`,data);  //1

    res.subscribe(result => {                                        //2
      if(data.type == "aws")
      {
        console.log("Updating AWS UI");
      }
      else if(data.type == "azure")
      {
        console.log("Updating AZURE UI");
        data[data.type].sasToken = tmpData;
      }
      else if(data.type == "local_lake")
      {
        console.log("Updating LOCAL_LAKE UI");
      }
    });

    return res;
  }

我想获得此代码的 100% 覆盖率,只需检查每个 'if' 块中的控制台消息即可。如何在 res.subscribe{} 块内进行测试?

只需模拟 http.post 并调用函数。

let httpClient : HttpClient;
httpClient = TestBed.get(HttpClient);
spyOn(httpClient,"post").and.returnValue(of(new HttpResponse()));
service.updateClientConfiguration(data.clientId,data).subscribe(response => {     
    expect(consoleSpy.calledWith(consoleMsg)).toBe(true);
 });