2017-01-22 89 views
0

我想单元测试我的指令,根据控制器变量设置表单有效性。 我的指令代码:单元测试指令与使用控制器的链接

angular.module('myModule',[]) 
 
     .directive('myDirective', function() { 
 
    return { 
 
     restrict: 'A', 
 
     link: function(scope, element, attr, ctrl) { 
 
      scope.$watch("mailExist", function(){ 
 
       if(scope.mailExist) { 
 
        ctrl.$setValidity('existingMailValidator', false); 
 
       } else { 
 
        ctrl.$setValidity('existingMailValidator', true); 
 
       } 
 
      }); 
 
     } 
 
    }; 
 
});

当试图单元测试这项指令,我试图找出与此代码控制器CTRL:

describe('directive module unit test implementation', function() { 
 
    var $scope, 
 
     ctrl, 
 
     form; 
 
    
 
    beforeEach(module('myModule')); 
 
    
 
    beforeEach(inject(function($compile, $rootScope) { 
 
     $scope = $rootScope; 
 
     var element =angular.element(
 
      '<form name="testform">' + 
 
       '<input name="testinput" user-mail-check>' + 
 
      '</form>' 
 
     ); 
 
     var ctrl = element.controller('userMailCheck'); 
 
     $compile(element)($scope); 
 
     $scope.$digest(); 
 
     form = $scope.testform; 
 
    })); 
 
     
 
    describe('userMailCheck directive test', function() { 
 
     it('should test initial state', function() { 
 
      expect(form.testinput.$valid).toBe(true); 
 
     }); 
 
    }); 
 
});

运行此测试,我仍然获得: 无法读取未定义的 属性'$ setValidity',这意味着我没有真正注入控制器。 我的测试有什么问题?

回答

0

最后,在找到了解决办法: 首先在代码我已经添加:

require: 'ngModel',

然后修改单元测试如下:

describe('directive module unit test implementation', function() { 
 
    var scope, 
 
     ngModel, 
 
     form; 
 
    
 
    beforeEach(module('myModule')); 
 
    
 
    beforeEach(inject(function($compile, $rootScope) { 
 
     scope = $rootScope.$new(); 
 
     var element =angular.element(
 
      '<form name="testform">' + 
 
       '<input name="testinput" ng-model="model" user-mail-check>' + 
 
      '</form>' 
 
     ); 
 
     var input = $compile(element)(scope); 
 
     ngModel = input.controller('ngModel'); 
 
     scope.$digest(); 
 
     form = scope.testform; 
 
    })); 
 
     
 
    describe('userMailCheck directive test', function() { 
 
     it('should test initial state', function() { 
 
      expect(form.testinput.$valid).toBe(true); 
 
     }); 
 
    }); 
 
});

和一切工作罚款。