mardi 2 février 2016

How to test a controller with injection

How to test a AngularJS controller with injection, for example:

angular.module('app', []).controller('PasswordController', passwordController);
     passwordController.$inject = ['$scope'];
     //does not exist in the documentation angularjs
   function passwordController($scope) {
      $scope.password = '';
      $scope.grade = function() {
        var size = $scope.password.length;
        if (size > 8) {
          $scope.strength = 'strong';
        } else if (size > 3) {
          $scope.strength = 'medium';
        } else {
          $scope.strength = 'weak';
        }
      };
   }

I can not get controller in the test writing

describe('PasswordController', function() {
  beforeEach(module('app'));
  var $controller;
  beforeEach(inject(function(_$controller_){
       $controller = _$controller_;
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      var $scope = {};
      var controller = $controller('PasswordController', { $scope: $scope });
      // TypeError: 'undefined' is not a function (evaluating '$controller('PasswordController');
      $scope.password = 'longerthaneightchars';
      $scope.grade();
      expect($scope.strength).toEqual('strong');
    });
  });
});

With the controller model of AngularJS documentation I managed to run the test: http://ift.tt/U9zu83

Aucun commentaire:

Enregistrer un commentaire