【问题标题】:AngularJS directive link function does not run in Jasmine testAngularJS 指令链接功能在 Jasmine 测试中不运行
【发布时间】:2015-09-11 23:32:13
【问题描述】:

在我的JSFiddle 我有这个指令。

(function() {

    angular.module('myApp', [])
        .directive('appFoo', appFoo);

    function appFoo() {

        console.log('Directive Factory runs');

        return {
            controller: AppFooController,
            link: link,
            replace: true,
            restrict: 'E',
            scope: {
                parentProp: '='
            }
        };

        function AppFooController($scope) {

            console.log('Controller runs');

            $scope.render({
                some: 'data'
            });

        }

        function link($scope, $element) {

            console.log('Link function runs');

            $scope.render = function(data) {
                console.log(shared.$scope.parentProp, $element[0], data);
            };

        }

    }

}());

还有这个茉莉花规格;

describe('myApp::appFoo', function() {

    var shared;

    beforeEach(function() {

        shared = {};
        shared.markup = '<app-foo parent-prop="someProp"></app-foo>';

        inject(function($compile, $rootScope) {
            shared.$compile = $compile;
            shared.$parentScope = $rootScope.$new(true);
            shared.$rootScope = $rootScope;
        });

        shared.createDirective = function() {
            shared.$element = angular.element(shared.markup);
            shared.$compile(shared.$element)(shared.$parentScope);
            shared.$parentScope.$digest();
            shared.el = shared.$element[0];
            shared.$childScope = shared.$element.scope();
        };

    });

    describe('when compiled', function() {

        describe('when all parameters are provided', function() {

            beforeEach(function() {
                shared.$parentScope.someProp = {
                    a: 'a',
                    b: 'b'
                };
                shared.createDirective();
            });

            it('should have a render method', function() {
                expect(typeof shared.$childScope.render).toEqual('function');
            });

        });

    });

});

链接函数的工作是向作用域添加一个渲染方法。它在应用程序中工作,但在 Jasmine 测试中它永远不会运行。

我已经查看了下面列出的各种其他问题,但没有运气。

任何帮助表示赞赏。

[1]

【问题讨论】:

  • 你确定它在应用程序中有效吗?我很确定控制器在链接功能之前首先被调用。因此,您在定义之前调用了 $scope.render。
  • 这是一个简化的测试用例,但是在它工作的应用程序中是可以的——尽管应用程序涉及网络,但我可能有竞争条件。正在调查,谢谢。

标签: javascript angularjs-directive jasmine


【解决方案1】:

正如@aliasm2k 所指出的,这里的问题是控制器在链接函数之前被调用。

因为控制器在链接函数创建之前调用了$scope.render,所以调用堆栈被放弃并且链接函数没有运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 2017-01-03
    • 2013-01-23
    • 2013-08-25
    • 1970-01-01
    • 2015-07-26
    相关资源
    最近更新 更多