I need to access the isolate scope of a directive in order to test the functions it contains. I have tried all the solutions that I found from SO. The problem is in the isolate scope of the directive, because if I don't set up the directive with isolate scope, the tests work fine.
我需要访问指令的隔离范围,以便测试它包含的函数。我尝试过从SO找到的所有解决方案。问题出在指令的隔离范围内,因为如果我没有使用隔离范围设置指令,那么测试工作正常。
My directive looks like this:
我的指令看起来像这样:
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;
}]);
The testing set-up looks like this:
测试设置如下所示:
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);
});
});
});
The output in console:
控制台中的输出:
TypeError: 'undefined' is not an object (evaluating '$scope.checkIfGoodCharactersOnly')
TypeError:'undefined'不是对象(评估'$ scope.checkIfGoodCharactersOnly')
1 个解决方案
#1
1
Since a form element wraps the input, I was attempting to access the scope of the form element, which does not exist.
由于表单元素包装输入,我试图访问表单元素的范围,该范围不存在。
This worked:
input = elem.find('input');
expect(input.isolateScope()).toBeDefined();
#1
1
Since a form element wraps the input, I was attempting to access the scope of the form element, which does not exist.
由于表单元素包装输入,我试图访问表单元素的范围,该范围不存在。
This worked:
input = elem.find('input');
expect(input.isolateScope()).toBeDefined();