微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular2 – http呼叫代码覆盖

我的组件是
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是,

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("$$$$$$$$$$$$$$$$**********$$$$$$$$$$$$$$$$$$$$$");
      });

  });

当我尝试运行测试用例.已经过去了但是,当我研究代码覆盖时,它不包括红色低于代码

请帮助获得完整的代码报道.谢谢.

在您在此处显示的测试中,您似乎没有从您的组件调用getHomePageData()

尝试建立这样的测试:

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","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测试函数中,您可以在进行异步操作的调用之后调用tick()来模拟一段时间,然后继续执行代码流.

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

编辑 – 错误案例

要测试错误逻辑,您可以使用mockRespond调用mockerror或设置错误响应:

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端点,它将返回错误.

因为我们在成功测试中分别测试错误和成功,所以无需在请求选项中添加错误相关的设置.

原文地址:https://www.jb51.cc/angularjs/142771.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐