Angular with Jasmine错误:无法找到指令所需的控制器

时间:2014-08-19 14:50:18

标签: angularjs jasmine

我有一个有两个指令的应用程序,其中一个指令需要另一个指令。我已经复制它以镜像应用程序的基础:

var module = angular.module('testApp', ['testApp.directiveA', 'testApp.directiveB']);

// Here goes your modules definition
module.controller('AppCtrl', function ($scope, $log) {
});

angular.module('testApp.directiveA', ['testApp.directiveB'])

.directive('directiveA', function () {
    return {
        restrict: 'EA',
    require: '^directiveB',
        template: '<div><h1>DirectiveA</h1></div>',
    scope: {
      value: "@"
    },
        link: function (scope, element, attrs, directiveBCtrl) {
            scope.testFunction = function() {
                return directiveBCtrl.exampleFunction();
            };

            scope.value = scope.testFunction();
        }
    }
});

angular.module('testApp.directiveB', [])

.directive('directiveB', function () {
    return {
        restrict: 'EA',
        template: '<div><h1>DirectiveB</h1></div>',
    scope: {
      value: "@"
    },
        controller: function ($scope) {
            $scope.exampleFunction = function() {
                return true;
            };
        }
    }
});

我正在尝试使用Jasmine编写测试来测试directiveA中的不同函数:

describe('Test directive with require', function () {

    var $scope, elem, scope;

    beforeEach(angular.mock.module("testApp.directiveA", "testApp.directiveB"));

    beforeEach(inject(function ($rootScope, $compile) {

        elem = angular.element('<directive-a value="aValue"></directive-a>');

        $scope = $rootScope.$new();

        $compile(elem)($scope);

        $scope.$digest();

        scope = elem.isolateScope();

    }));

    it('Should test a function on directiveA', function() {

        var result = scope.testFunction();
        expect(result).toEqual(true);
    });
});

当我运行时,我收到错误:

Controller 'directiveB', required by directive 'directiveA', can't be found!

我设置了一个重现错误的Plnkr。我似乎无法弄清楚如何将一个指令或其控制器注入另一个指令。任何帮助都非常感谢。

http://plnkr.co/edit/pKDNkiO1ZHxE6qQKXXF5?p=preview

1 个答案:

答案 0 :(得分:1)

以下是更新的茉莉花beforeEach代码(或plunker):

beforeEach(inject(function($rootScope, $compile) {
    elem = angular.element('<directive-b><directive-a value="aValue"></directive-a></directive-b>');
    $scope = $rootScope.$new();
    $compile(elem)($scope);
    $scope.$digest();
    scope = elem.children(':first').isolateScope();
}));

更新了directiveB代码:

directive('directiveB', function() {
    return {
        restrict: 'EA',
        //template: '<div><h1>DirectiveB</h1></div>',
        scope: {
            value: "@"
        },
        controller: function($scope) {
            this.exampleFunction = function() {
                return true;
            };
        }
    }
});

外卖:

  1. 将您的指令包装到必需的指令中,并使用elem.children(':first').isolateScope()
  2. 获取其范围
  3. 必需的指令不应该有模板,否则它将覆盖您的指令indside
  4. 使用this创建控制器方法,而不是$scope
  5. <强> UPD:

    如果父指令需要有模板,则可以使用transclude。这是pluker