[英]How to access the scope of the directive in Jasmine Test
I cant get the scope of my directive (another option is that I get the scope but my function is not there). 我无法获得指令的范围(另一种选择是获得范围但我的功能不存在)。 I am using Jasmine over Karma. 我在Karma上使用Jasmine。
My directive: 我的指令:
angular.module('taskApp').directive('nkAlertDir', ['$http', function ($http) {
return {
template: "<span>{{msg}}</span>",
replace: true,
link: function (scope, elem, attrs) {
scope.values = {
canvas: canvasSize,
radius: size,
center: canvasSize / 2
};
$http.get('someUrl')
.suncces(function (data) {
scope.msg = data;
})
.error(function (err) {
//there is always be error because this url does nor exist
//but this is not the point in this exercise
});
scope.returnNumbers = function () {
return [2, 2];
}
}
}
}]);
My test: 我的测试:
describe('Unit: Directives', function () {
var element;
var scope;
beforeEach(module('taskApp'));
beforeEach(inject(function ($compile, $rootScope) {
scope = $rootScope;
element = angular.element('<div nk-alert-dir></div>');
scope.size = 100;
$compile(element)(scope);
scope.$digest();
}));
it('should bind an alert message of "task added!"', function () {
var dirScope = element.isolateScope();
console.log(dirScope);
});
});
Somehow I always get the dirScope is undefined I have tried this: 不知何故,我总是得到dirScope是未定义的,我已经试过了:
digest()
in $apply()
替换$apply()
的digest()
$apply()
$rootScope
in $rootScope.$new()
将$rootScope
替换为$rootScope
$rootScope.$new()
You don't have an isolated scope in your directive, so element.isolateScope()
is going to return undefined. 您的指令中没有隔离的范围,因此element.isolateScope()
将返回未定义的范围。
Try just accessing the scope: element.scope()
尝试仅访问范围: element.scope()
If you want an isolate scope on your directive, then you have to set the scope
property of your directive definition object to a JS object and add the properties there. 如果要在指令上使用隔离范围,则必须将指令定义对象的scope
属性设置为JS对象,然后在其中添加属性。 Then you'd be able to use element.isolateScope
to get access to the isolate scope. 然后,您将能够使用element.isolateScope
来访问隔离范围。
return {
template: "<span>{{msg}}</span>",
replace: true,
scope : {}, // Any properties you want to pass in to the directive on scope would get defined here
link: function (scope, elem, attrs) {
scope.values = {
canvas: canvasSize,
radius: size,
center: canvasSize / 2
};
$http.get('someUrl')
.suncces(function (data) {
scope.msg = data;
})
.error(function (err) {
//there is always be error because this url does nor exist
//but this is not the point in this exercise
});
scope.returnNumbers = function () {
return [2, 2];
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.