简体   繁体   English

无法弄清楚为什么res.json()没有在单元测试覆盖率Angular中命中

[英]Can't figure out why res.json() is not hit in Unit Test Coverage, Angular

So I have a Unit Test Coverage being tracked by the karma-coverage-instanbul-reporter, when I look at the coverage report though, the: 因此,当我查看报道报告时,我有一个单位测试覆盖范围由业力覆盖 - 实例 - 记者跟踪,:

.map(res => res.json())

portion of all of my Providers is never hit in the test. 我所有提供商的一部分从未在测试中受到影响。 But I do have tests for those Providers, and am verifying that I'm getting a response. 但我确实对那些提供商进行了测试,并且正在验证我是否得到了回复。

Here is an example of on the functions I'm testing: 以下是我正在测试的函数的示例:

public getCampaigns(): Observable<CampaignsResponse> {
  return this.http.get(this.campaignsUrl).map(res => res.json());
}

Here is the test for this function: 以下是此功能的测试:

describe("getCampaigns", () => {
  it("should return an Observable<CampaignsResponse>",
    inject([CampaignsService, MockBackend], (service: CampaignsService, mockBackend: MockBackend) => {
      // arrange
      mockBackend.connections.subscribe((connection: any) => {
        connection.mockBackend(new Response(new ResponseOptions({
          body: JSON.stringify(mockCampaigns),
        })));
      });

      // act
      service.getCampaigns().subscribe((campaigns) => {
        // assert
        expect(campaigns.campaigns.length).toEqual(1);
   expect(campaigns.campaigns[0].id).toEqual(mockCampaigns.campaigns[0].id);
      expect(campaigns.campaigns[0].channelID).toEqual(mockCampaigns.campaigns[0].channelID);
      expect(campaigns.campaigns[0].name).toEqual(mockCampaigns.campaigns[0].name);
      expect(campaigns.campaigns[0].active).toEqual(mockCampaigns.campaigns[0].active);
      expect(campaigns.campaigns[0].createdAt).toEqual(mockCampaigns.campaigns[0].createdAt);
      expect(campaigns.campaigns[0].updatedAt).toEqual(mockCampaigns.campaigns[0].updatedAt);
    });
}));

}); });

But according to my test coverage res.json() is never hit inside the map function. 但根据我的测试覆盖率,res.json()永远不会在地图功能中被击中。

Does anyone have any ideas on why that might be? 有没有人对这可能是什么有任何想法? Is it possible that the Coverage report is just wrong or is mapping the code incorrectly back to TypeScript? Coverage报告可能是错误的还是将代码错误地映射回TypeScript?

Your connection has the type MockConnection instead of any , and MockConnection does not have a mockBackend property. 您的connection具有MockConnection类型而不是any类型,并且MockConnection没有mockBackend属性。 Instead, it has a mockRespond . 相反,它有一个mockRespond https://angular.io/docs/ts/latest/api/http/testing/index/MockConnection-class.html https://angular.io/docs/ts/latest/api/http/testing/index/MockConnection-class.html

Try modifying the test like this: 尝试修改测试,如下所示:

// arrange
mockBackend.connections.subscribe((connection: MockConnection) => {
  connection.mockRespond(new Response(new ResponseOptions({
    body: JSON.stringify(mockCampaigns),
  })));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM