2015-12-23 60 views
2

最近我們開始爲我們的應用程序編寫測試用例,我們需要幫助編寫控制器的測試用例。我們使用Mocha,chai和Snion庫來編寫測試用例。如何在Angular js中爲控制器編寫測試用例

這裏是包含我們的控制器代碼的plunker鏈接。任何人都可以幫助我們如何編寫這個控制器的測試用例嗎?我們將在此基礎上實施其餘部分。我們需要使用此控制器進行初始推送。

http://plnkr.co/edit/oginuqO0afxnWbVMos0f?p=info

下面是代碼:

angular.module('ngBoilerplate.account', [ 
    'ui.router','ngAnimate', 'ui.bootstrap','ngBoilerplate.contact','ngResource','jcs-autoValidate','ngCookies','ngTagsInput' 
]) 
.controller('addAccount', function($scope,industryService,$http,$state,LoggedUser){ 
    $scope.industry = []; 
    industryService.query().$promise.then(function(data) { 
     $scope.industry = data; 
    }); 

    window.onbeforeunload = function (event) { 

     if ($scope.addAccountForm.$dirty) { 

      var message = 'If you leave this page you are going to lose all the unsaved changes.'; 

      if (typeof event == 'undefined') { 
       event = window.event; 
      } 
      if (event) { 
       event.returnValue = message; 
      } 

      return message; 
     } 
    }; 

    $scope.insertAccount = function(){ 
     $scope.address = { 
      'line1':$scope.line1, 
      'line2':$scope.line2, 
      'city':$scope.city, 
      'zipCode':$scope.zipCode, 
      'state':$scope.state, 
      'country':$scope.country 
     }; 

     console.log($scope.industryId); 

     if($scope.industryId!== undefined) { 

      $scope.industry = { 
       'id' : $scope.industryId 
      }; 
     } 

     $http.post('/rest/users/'+LoggedUser.getUserName()+'/accounts',{ 
      'name' : $scope.name, 
      'industryBean': $scope.industry, 
      'email' :$scope.email, 
      'phone' : $scope.phone, 
      'fax' : $scope.fax, 
      'website' : $scope.website, 
      'headquarters' : $scope.headquarters, 
      'dbaName' : $scope.dbaName, 
      'numberOfEmployees' : $scope.numberOfEmployees, 
      'annualRevenue':$scope.annualRevenue, 
      'logo' : $scope.logo, 
      'primaryContact': $scope.contact, 
      'addressBean':$scope.address 
     }).success(function(data){ 
      $scope.account=data; 
      $state.go('main.account', {}, {reload: true}); 
     }); 
    }; 
}) 
.factory("loggedInUser", function($resource) { 
    return $resource("/rest/users/:username"); 
}) 
.factory("industryService", function($resource) { 
    return $resource("/rest/accounts/industry"); 
}) 

任何幫助非常感謝。

在此先感謝,如果您對此有任何疑問,請告知我。

回答

1

我喜歡摩卡柴和Sinon,並使用它們來測試節點代碼。從未使用過Angular。

典型的Angular設置是Karma,Jasmine(單元測試)和量角器(E2E測試)。

看着你的控制器代碼,我會說你在控制器中有太多的邏輯。您需要將某些代碼降級到某個服務。

在測試$ http方面,您需要使用ng-mock的$ httpBackend。

您應該在代碼中使用Angular Controller As語法。

+0

謝謝你的答案兄弟...它絕對有幫助...我會嘗試這個。 –

相關問題