【发布时间】: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