gpt4 book ai didi

javascript - Jasmine 测试中从未调用 AngularJS 指令的链接函数

转载 作者:行者123 更新时间:2023-12-02 15:00:37 26 4
gpt4 key购买 nike

我不明白为什么我的指令的链接函数在 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

关于javascript - Jasmine 测试中从未调用 AngularJS 指令的链接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35453157/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com