$ ionicPopup.show按钮onTap函数未在Angular Jasmine单元测试中获得覆盖

时间:2017-10-19 18:38:03

标签: angularjs unit-testing karma-jasmine test-coverage ionicpopup

当我在单元测试规范文件中调用outOfMvp()函数时,除了onTap函数之外,函数内部的所有内容都会被覆盖。 我想知道如何在我的单元测试中获得按钮的onTap函数的覆盖率,该函数在$ ionicPopup.show()方法中传递的JSON对象中?

这是js文件中的函数:

function outOfMvp(data) {
  environmentConfig.isScanDataReadValid = false;
  popup = $ionicPopup.show({
    title: kioskConstants.POPUP_WORDING.OUT_OF_MVP_RETURN.title,
    template: data.returnRejectReasons[0].description
    + '.<br><br>' + kioskConstants.POPUP_WORDING.OUT_OF_MVP_RETURN.template
    + ' <span style=\'color:#007dc6\'>' + data.orderNo + '</span>',
    cssClass: 'popup-container-small',
    buttons: [
      {
        text: "OK",
        type: "bottom-button green narrow",
        onTap: function () {
          if ($state.current.name != "order-history") {
            environmentConfig.isScanDataReadValid = true;
            $rootScope.$broadcast("CancelConnectQR", data.orderNo);
            OrderInfo.init();
            $state.go(kioskConstants.ROUTE_STATE_LANDING_PAGE);
          }
        }
      }
    ]
  });
}

在spec文件中对outOfMvp函数进行单元测试:

describe('If call customPopupWidget.outOfMvp(data) function',function () {

it('it should call $ionicPopup.show().', function () {
  customPopupWidget.outOfMvp(data);
  expect(ionicPopup.show).toHaveBeenCalled();
});

覆盖outOfMvp函数的html文件: enter image description here

1 个答案:

答案 0 :(得分:0)

您需要进行一些修改,以确保在单元测试的帮助下代码是否可以正常工作。

尝试一下:

function outOfMvp(data) {
  environmentConfig.isScanDataReadValid = false;
  popup = $ionicPopup.show({
    title: kioskConstants.POPUP_WORDING.OUT_OF_MVP_RETURN.title,
    template: data.returnRejectReasons[0].description
    + '.<br><br>' + kioskConstants.POPUP_WORDING.OUT_OF_MVP_RETURN.template
    + ' <span style=\'color:#007dc6\'>' + data.orderNo + '</span>',
    cssClass: 'popup-container-small',
    buttons: [
      {
        text: "OK",
        type: "bottom-button green narrow",
        onTap: function () {
          return true;
        }
      }
    ]
  });
  popup.then(function(response){
     if(response){ //when response is true
       if ($state.current.name != "order-history") {
         environmentConfig.isScanDataReadValid = true;
         $rootScope.$broadcast("CancelConnectQR", data.orderNo);
         OrderInfo.init();
         $state.go(kioskConstants.ROUTE_STATE_LANDING_PAGE);
       }
     }
  })
}

您可以按以下方式测试上面的代码:

describe('If call customPopupWidget.outOfMvp(data) function',function () {

it('it should call $ionicPopup.show().', function () {
  spyOn($ionicPopup, 'show').and.callFake(function() {
     return $q.resolve(true);
  })
  customPopupWidget.outOfMvp(data);
  expect(ionicPopup.show).toHaveBeenCalled();
});

别忘了注入$ ionicPopup,$ q否则会出错。您需要记住的一件事是您不会获得此代码的覆盖范围:

onTap: function () {
   return true;
}

但是您的代码将在逻辑上完整的覆盖范围内进行测试,因为它将在点击“确定”按钮时测试您想要执行的操作。