How to mock angular directive that has require field

258 views Asked by At

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

There are 1 answers

2
Huston Hedinger On BEST ANSWER

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