Angular2 - http调用代码覆盖率 [英] Angular2 - http call Code coverage

查看:126
本文介绍了Angular2 - http调用代码覆盖率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的components.ts是,

My components.ts is,

 getHomePageData() : void{
    this.homeservice.getHomePageData()
          .subscribe(
              data =>   {

                            //console.log("response status ################### "+data.status);
                            //console.log("getUserData response ************ \n"+JSON.stringify(data));
                            this.defaultFacilityId = data.response.defaultFacilityId;
                            this.defaultFacilityName = data.response.defaultFacilityName;
                            this.enterpriseId = data.response.enterpriseId;
                            this.enterpriseName = data.response.enterpriseName;
                            this.facilityList = data.response.facilityList;
                            this.userName = data.response.userName;

                            this.showDefaultPopoup();
                        },
              error =>  {
                            console.error(error);
                            //this.errorMessage="Technical error - Contact Support team !" ;
                        }
          );

  }

所以我的component.spec.ts是,

So my component.spec.ts is ,

 it('getHomePageData with SUCCESS - getHomePageData()', () => {
    backend.connections.subscribe((connection: MockConnection) => {
      //expect(connection.request.url).toEqual('http://localhost:8080/MSMTestWebApp/UDM/UdmService/Home/');
      expect(connection.request.url).toEqual('http://192.168.61.158:9080/GetUserData');

      expect(connection.request.method).toEqual(RequestMethod.Get);
      expect(connection.request.headers.get('Content-Type')).toEqual('application/json');
      let options = new ResponseOptions({
        body:
        {
          "request": { "url": "/getUserData" },
          "response": {
                 "defaultFacilityName":"3M Health Information Systems",
                  "enterpriseId":"11.0",
                  "enterpriseName":"HSA Enterprise",
                  "defaultFacilityId": "55303.0",
                  "userName":"Anand"
          },
          "error": ""
        },
        status : 200
      });

      connection.mockRespond(new Response(options));

    });

     backend.connections.subscribe((data) => {
      //expect(data.response.facilityId).toEqual("55303.0");
      //expect(subject.handleError).toHaveBeenCalled();
    })

    service.getHomePageData().subscribe((data) => {
          //expect(videos.length).toBe(4);
          expect(data.response.defaultFacilityId).toEqual("55303.0");
          component.defaultFacilityId = data.response.defaultFacilityId;
          component.defaultFacilityName = data.response.defaultFacilityName;
          component.enterpriseId = data.response.enterpriseId;
          component.enterpriseName = data.response.enterpriseName;
          component.userName = data.response.userName;
          console.log("$$$$$$$$$$$$$$$$**********$$$$$$$$$$$$$$$$$$$$$");
      });

  });

当我尝试运行测试用例时。它通过了。但是,当我查看代码覆盖率时,它不包括

When i try to run test case. It got passed. But while I look into the code coverage, it doesn't cover the code shown in red below

请帮助获取完整的代码覆盖率。谢谢。

Please help to get the full code coverage. Thanks.

推荐答案

在你看到的测试中,你似乎没有调用 getHomePageData ()来自您的组件

In the test you've shown here you don't seem to be calling getHomePageData() from your component

尝试构建您的测试:

import { fakeAsync, tick } from '@angular/core/testing';
...
it('getHomePageData with SUCCESS - getHomePageData()', fakeAsync(() => {
  backend.connections.subscribe((connection: MockConnection) => {
  //expect(connection.request.url).toEqual('http://localhost:8080/MSMTestWebApp/UDM/UdmService/Home/');
  expect(connection.request.url).toEqual('http://192.168.61.158:9080/GetUserData');

  expect(connection.request.method).toEqual(RequestMethod.Get);
  expect(connection.request.headers.get('Content-Type')).toEqual('application/json');
  let options = new ResponseOptions({
    body:
    {
      "request": { "url": "/getUserData" },
      "response": {
             "defaultFacilityName":"3M Health Information Systems",
              "enterpriseId":"11.0",
              "enterpriseName":"HSA Enterprise",
              "defaultFacilityId": "55303.0",
              "userName":"Anand"
      },
      "error": ""
    },
    status : 200
  });

  connection.mockRespond(new Response(options));

  });

  // If this function is not automatically called in the component initialisation
  component.getHomePageData();
  tick();
  //you can call expects on your component's properties now
  expect(component.defaultFacilityId).toEqual("55303.0");

});

FakeAsync 允许你在一个更线性的风格,所以你不再需要订阅服务功能来写下你的期望。

FakeAsync allows you to write tests in a more linear style so you no longer have to subscribe to the service function to write your expectations.

FakeAsync 测试函数,你可以在调用之后调用 tick()进行异步操作以模拟一段时间,然后继续代码流。

In a FakeAsync test function you can call tick() after a call where an asynchronous operation takes place to simulate a passage of time and then continue with the flow of your code.

你可以在这里阅读更多相关信息: https://angular.io/docs/ts/latest/testing/#!#fake-async

You can read more about this here: https://angular.io/docs/ts/latest/testing/#!#fake-async

编辑 - 错误大小写

要测试错误逻辑,您可以调用 mockError 或使用错误响应设置您的连接上的 mockRespond

To test the error logic you can call mockError or set up an error response using mockRespond on your connection:

it('getHomePageData with ERROR- getHomePageData()', fakeAsync(() => {
  backend.connections.subscribe((connection: MockConnection) => {
    if (connection.request.url === 'http://192.168.61.158:9080/GetUserData') {
        // mockError option
        connection.mockError(new Error('Some error'));
        // mockRespond option
        connection.mockRespond(new Response(new ResponseOptions({
          status: 404,
          statusText: 'URL not Found',
        })));
    }

  component.getHomePageData();
  tick();
  //you can call expects now
  expect(connection.request.url).toEqual('http://192.168.61.158:9080/GetUserData');
  expect(connection.request.method).toEqual(RequestMethod.Get);
  expect(connection.request.headers.get('Content-Type')).toEqual('application/json');
  expect('you can test your error logic here');
});

我们在订阅中做的是确保随时 GetUserData 在此测试方法中调用端点将返回错误。

What we're doing inside the subscription is making sure that anytime the GetUserData endpoint is called within this test method it will return an error.

因为我们在成功测试中分别测试错误和成功,所以没有必要在请求选项中添加与错误相关的设置。

Because we test errors and successes separately in the success test there's no need to add the error related settings in the request options.

这篇关于Angular2 - http调用代码覆盖率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆