【问题标题】:How to mock angular directive that has require field如何模拟具有要求字段的角度指令
【发布时间】:2015-08-30 04:24:59
【问题描述】:

我最近遇到了这个问题: 我有:directive-adirective-b

Directive-b 有一个 `require: '^directive-a' 字段,这使得单元测试变得不可能。

我曾经在单元测试中以这种方式编译指令:

element = $compile('<directive-a></directive-a>')($scope);

然后我可以用element.isolateScope()得到隔离作用域

但是现在因为 b 依赖于 a,我不得不这样做:

element = $compile('<directive-a> <directive-b></directive-b> </directive-a>')($scope);

在这种情况下,element.isolateScope() 返回指令 a 的作用域而不是指令 b。

如何获取directive-b的范围?

演示:

指令 A:

(function(){
'use strict';

function directiveA(){
    return {
        restrict: 'E',
        templateUrl: '/main/templates/directiveA.html',
        transclude: true,
        scope: {
            attr1: '='
        },
        controller: function($scope){
            //code...
        },
        link: function($scope, element, attrs, ctrl, transclude){
            injectContentIntoTemplate();

            function injectContentIntoTemplate(){
                transclude(function (clone) {
                    element.find('#specificElement').append(clone);
                });
            }
        }
    };
}

angular
    .module('myModule')
    .directive('directiveA', directiveA);
}());

指令 B:

(function(){
'use strict';

function directiveB(){
    return {
        restrict: 'E',
        templateUrl: '/main/templates/directiveA.html',
        transclude: true,
        replace: true,
        scope: {
            attr1: '@'
        },
        require: '^directiveA',
        link: function ($scope, element, attrs, ctrl) {
            $scope.customVariable = 'something';
        }
    };
}

angular
    .module('myModule')
    .directive('directiveB', directiveB);
}());

【问题讨论】:

    标签: javascript angularjs unit-testing angular-directive


    【解决方案1】:

    迟到的答案,未经测试。

    let element = $compile('<directive-a> <directive-b></directive-b> </directive-a>')($scope);
    let elementB = element.find('directive-b');
    let BsScope = elementB.isolateScope();
    

    【讨论】:

    • 谢谢@Huston,但我的问题是如何模拟而不是如何编译。这是两种不同的解决方案。而且我更喜欢模拟我的内部指令而不是也执行它。
    • 人力资源部。您的问题是关于访问内部指令的范围,这就是我试图回答的问题。如果您对如何模拟内部指令还有其他问题,那么您也应该问那个问题。 ;-)
    猜你喜欢
    • 2015-02-11
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2020-01-21
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    相关资源
    最近更新 更多