我需要访问指令的隔离范围才能测试它包含的函数。我尝试过从SO找到的所有解决方案。问题在于指令的隔离范围,因为如果我没有使用隔离范围设置指令,那么测试工作正常。
我的指示如下:
angular.module('validators').directive('validateName', [function() {
var directive = {};
directive.restrict = "A";
directive.require = 'ngModel';
directive.scope = {};
directive.link = function(scope, element, attrs, ngModel) {
scope.checkIfGoodCharactersOnly = function(name) {
if ( name.match(/[0-9!$%^&*@#()_+|~=`{}\[\]:";'<>?,.\/]/g) ) {
return false;
} else {
return true;
}
};
};
return directive;
}]);
测试设置如下所示:
beforeEach(module('validators'));
describe('Directive: validateName', function () {
var $scope, elem;
beforeEach(
inject(function ($compile, $rootScope) {
$scope = $rootScope.$new();
elem = angular.element('<form name="form">' +
'<input name="name" ng-model="transaction.name" validate-name />' +
'</form>');
elem = $compile(elem)($scope);
$scope = elem.isolateScope();
}));
describe("Link", function() {
it("Should call checkIfGoodCharactersOnly", function() {
expect($scope.checkIfGoodCharactersOnly("abcd")).toEqual(true);
});
});
});
控制台中的输出:
TypeError:&#39; undefined&#39;不是一个对象(评估&#39; $ scope.checkIfGoodCharactersOnly&#39;)
答案 0 :(得分:1)
由于表单元素包装输入,我试图访问表单元素的范围,该范围不存在。
这有效:
input = elem.find('input');
expect(input.isolateScope()).toBeDefined();