使用控制器的链接的单元测试指令



我正在尝试对我的指令进行单元测试,该指令根据控制器变量设置表单有效性。我的指令代码:

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"这意味着我还没有真正注入控制器。我的测试出了什么问题?

终于找到了解决方案:我首先在代码中添加:

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);
       }); 
    });
});

一切都很好。

最新更新