如何模拟具有require字段的angular指令

时间:2015-06-14 17:09:54

标签: javascript angularjs unit-testing angular-directive

我最近遇到了这个问题: 我有:directive-belement = $compile('<directive-a></directive-a>')($scope);

指令-b有一个`要求:&#39; ^指令-a&#39;使单元测试无法进行的领域。

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

element.isolateScope()

然后我可以使用element = $compile('<directive-a> <directive-b></directive-b> </directive-a>')($scope);

获取隔离范围

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

element.isolateScope()

在这种情况下,directive-b返回指令-a的范围而不是指令-b。

如何获得(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); }()); 的范围?

演示:

指令A:

(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);
}());

指令B:

switch (oldVersion) {
    case 1: upgradeFromV1();
    case 2: upgradeFromV2(); 
    case 3: upgradeFromV3();
}

1 个答案:

答案 0 :(得分:0)

迟到的答案,未经测试。

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