我正在尝试 访问范围附带的 Controller **我的自定义 Angular 指令** 当 Jasmine 测试 .
app.directive('MyDirective', function(){
return {
template:...,
scope:...,
controller: function($scope){
$scope.clickMe = function() {
....
};
$scope.message = "";
}
}
我想在 jasmine 中编写一个测试来验证是否定义了 clickMe 方法。
it('should have 3 methods', function() {
expect(dscope).not.toBe(null);
expect(scope).not.toBe(null);
expect(angular.isFunction(dscope.clickMe)).toBe(true);
expect(dscope.message).toBe(true); }
在 beforeEach() 中,我声明了 scope 和 dscope 变量,如下所示:
beforeEach(inject(function( $rootScope, $compile){
scope = $rootScope.$new();
element = angular.element("<div my-directive></div>");
//bind the empty scope into the directive
$compile(element)(scope);
//access to internal directive scope of our element
dscope = element.scope(); }));
但是当我运行测试时,我得到“ 期望 false 为真。”* 并期望 undefined 对于 scope.message 不为 null
最佳答案
如果您使用的是 Angular 1.2+,则必须使用...
dscope = element.isolateScope();
代替...
dscope = element.scope();
访问隔离的范围。我无法判断您的范围是否是孤立的,因为您在问题中省略了指令的范围声明,但我想这就是这里发生的事情。
见 this Github 上的 issue 以解释 .scope() 和 .isolateScope() 之间的区别
关于angularjs - 在 Jasmine 测试中获取自定义指令的 Controller 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24182756/