AngularJS指令的链接函数从未在Jasmine测试中调用过
link function of AngularJS directive never called in Jasmine test
我不明白为什么我的指令的链接函数在 Jasmine 测试中从未被调用。我举了一个简单的例子。
这是我的指令(TestDirective.js(:
'use strict';
angular.module('comp-one').directive('test',function(){
return{
restrict:'E',
templateUrl:'components/comp-one/html/TestTemplate.html',
scope:true,
link:function(scope){
scope.test='xxx';
}
};
});
这是测试用例:
'use strict';
describe('testDirective',function(){
var $compile, $rootScope, element;
beforeEach(module('comp-one'));
beforeEach(module('templates'));
beforeEach(inject(function(_$rootScope_,_$compile_){
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('xxx', function(){
var html = '<test></test>';
element = $compile(html)($rootScope);
$rootScope.$digest();
expect( $rootScope.test ).toBe('xxx');
});
});
测试失败了,因为链接函数永远不会被调用,所以 xxx 变量是未定义的。我预计链接功能会被"$compile(html(($rootScope(;"语句超越。当我在链接函数中设置断点并在浏览器中运行应用程序(而不是测试(时,将调用链接函数。
我正在使用 Karma 运行测试,它还找到了我在控制台输出中看到的文件:
Processing "D:/JWS/test/workspace/bla/app/components/comp-one/scripts/TestDirective.js".
编辑:
好当我将范围设置为 false 时,我发现测试运行成功。但是有没有办法用隔离的范围测试链接功能呢?
调用链接函数。您将在元素的作用域中找到该值,而不是在$rootScope
上找到该值。
在期望部分中使用element.isolateScope().test
而不是$rootScope.test
。
相关文章:
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- Jasmine单元测试在监视服务方法时失败
- 如何使用Jasmine测试Knockout.js点击绑定
- 如何在jasmine测试中为有角度的项目注入依赖项
- 测试iFrame的位置.href是在jasmine单元测试中设置的
- 在Karma Jasmine单元测试用例中检查日期格式
- Jasmine:测试setTimeout函数会抛出一个错误
- 如何通过 phantomjs 可靠地执行利用 requirejs 的 Jasmine 测试
- 当使用Jasmine在JS中测试AJAX调用时,.andReturn(..)和.respondWith(
- 使用jasmine测试JavaScript回调函数
- 如何在Jasmine/Rect中测试带有范围输入的“onChange”事件
- Jasmine测试工厂函数调用本地函数和另一个函数-获取错误:应该是间谍,但得到了function
- 使用$httpBackend测试Jasmine/Karma的AngularJS不起作用
- 如何测试Jasmine设置代码
- 测试Jasmine测试是否失败
- expect - response在AngularJS单元测试(Jasmine)中不起作用
- 重构单元测试(Jasmine)
- 测试Jasmine中的Rails Route
- 使用特定的keyCode测试Jasmine中的keydown事件
- 单元测试——jasmine, javascript