【问题标题】:unit testing directive with link using controller使用控制器链接的单元测试指令
【发布时间】:2017-01-22 14:42:06
【问题描述】:

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

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

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive


    【解决方案1】:

    终于找到了解决办法: 首先在我添加的代码中:

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

    一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-14
      • 2014-02-06
      • 2018-12-04
      • 2014-05-23
      • 2015-10-03
      • 2014-02-08
      • 1970-01-01
      • 2021-03-29
      相关资源
      最近更新 更多