如何测试Angular指令的控制器?

时间:2015-10-02 05:57:45

标签: angularjs unit-testing scope controller directive

我在测试指令的控制器时遇到问题。我搜索的每个地方似乎都显示出我正在做的事情,但是当我尝试在我的范围内调用方法时,它们似乎并不存在。

可能我错过了一些明显的东西,有人能看到吗?

以下是我的代码的简化示例:

myDirective.js

angular.module("app").directive("myDirective", function() {
    return {
        restrict: "E",
        templateUrl: "templates/my-directive.html",
        controller: function($scope) {

            $scope.myMethod = function() {
                /**....**/
            };
        }
    };
});

myDirectiveTest.js

describe("myDirective", function() {

    var scope, element;

    beforeEach(module("app"));
    // uses karma-ng-html2js-preprocessor
    beforeEach(module("templates/my-directive.html"));

    beforeEach(inject(function ($rootScope, $compile) {
        scope = $rootScope.$new();

        element = angular.element("<my-directive></my-directive>");

        $compile(element)(scope);
        scope.$digest();
    }));

    it("should have method defined", function() {
        // this fails
        expect(scope.myMethod).toBeDefined();
    });
});

谢谢!我正在使用Jasmine&amp;噶

1 个答案:

答案 0 :(得分:0)

使用简化代码的快速Plunker似乎可行。 (http://plnkr.co/edit/5kFq3kfbnrdRObapWTx6)。

我只使用内联模板替换了指令中的模板url:

template: '<div></div>'

,但这不应该有所作为。因此,也许有些东西不能用于测试设置,或者您在简化示例代码时纠正了自己的错误。

这可能更符合评论的条件,但没有发表评论的声誉

相关问题