2017-01-22 69 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); 
 
     }); 
 
    }); 
 
});

和一切工作罰款。