2016-10-25 75 views
0

如何爲我的AngularJS控制器LoginController創建單元測試?如何爲此示例模擬AuthenticationService? 我的控制器是否使用模型正確構建了單元測試&?如何在AngularJS中爲控制器創建單元測試

控制器的LoginController代碼:

layoutControllers.controller('LoginController', 
    ['$scope', '$rootScope', '$location', 'AuthenticationService', 
    function ($scope, $rootScope, $location, AuthenticationService) { 

     AuthenticationService.ClearCredentials(); 

     $scope.login = function() { 
      $scope.dataLoading = true; 
      AuthenticationService.Login($scope.email, $scope.password, function (response) { 
       AuthenticationService.SetCredentials($scope.email, $scope.password, response.UserId); 
       $scope._showValidationErrors(null, null); 
       $location.path('/'); 

      }, function (response) { 
       $scope._showValidationErrors(response.Errors, response.OtherErrors); 
      }); 
      $scope.dataLoading = false; 
     }; 

     $scope._showValidationErrors = function (errors, otherErrors) { 
      $scope.validationErrors = []; 
      $scope.errors = {}; 
      $scope.errors.form = {}; 

      if (errors && angular.isArray(errors)) { 
       for (var errorCounter in errors) { 
        $scope.validationErrors.push(errors[errorCounter].Message); 
        $scope.errors.form[errors[errorCounter].Key] = errors[errorCounter].Message; 
       } 
       // debugger; 
      } 

      if (otherErrors && angular.isArray(otherErrors)) { 
       for (var errorCounter2 in otherErrors) { 
        $scope.validationErrors.push(otherErrors[errorCounter2]); 
       } 
      } 
     } 

    }]); 

回答

0

嘗試https://docs.angularjs.org/guide/unit-testing

結帳測試一個控制器部分

報價: -

因爲控制器不是可在全球範圍內,我們需要先使用angular.mock.inject注入我們的控制器。

describe('LoginController', function() { 
     beforeEach(module('app')); 

     var $controller; 

     beforeEach(inject(function(_$controller_){ 
     // The injector unwraps the underscores (_) from around the parameter names when matching 
     $controller = _$controller_; 
     })); 

     describe('My auth test', function() { 
     it('success login will not display validation erreors', function() { 
      var $scope = {}; 
      var controller = $controller('LoginController', { $scope: $scope }); 

      $scope.login(); 
      //test for $scope.validationErrors 
      expect($scope.validationErrors).toBeUndefined(); 
     }); 

     it('failure login will has validation errors', function() { 
      var $scope = {}; 
      var controller = $controller('LoginController', { $scope: $scope }); 

      $scope.login(); 
      //test for $scope.validationErrors 
      expect($scope.validationErrors).not.toBeUndefined(); 
      expect($scope.validationErrors.length).not.toBeGreaterThan(0); 
     }); 
     }); 
    }); 
+0

從我的知識:),它不運行測試:)。嘲笑AU證書服務呢?沒有cerdentails設置。它不會工作:) –

+0

這將測試你的'login()'函數,它是你的實際代碼。你可以捕獲它對$ scope或其他對象的影響,比如$ location等。你能描述一下你在考慮作爲一個被測試的單元嗎? – bhantol

+0

認證服務怎麼樣?這是依賴性。我認爲它應該被嘲笑只測試控制器。但我可能是錯的。 –

相關問題