简体   繁体   中英

How to mock angular directive that has require field

I've recently met with this problem: I have: directive-a , directive-b

Directive-b has a `require: '^directive-a' fields which makes unit testing impossible.

I used to compile directive in this way in my unit tests:

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

Then I can get the isolated scope with element.isolateScope()

But now because b has a dependency on a, i had to do like this:

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

And in this case element.isolateScope() returns directive-a's scope instead of directive-b.

How can I get the scope of directive-b ?

Demo:

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

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

Late answer, and untested.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM