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

link function of AngularJS directive never called in Jasmine test

本文关键字:测试 Jasmine 调用 指令 链接 函数 AngularJS      更新时间:2023-09-26

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