【问题标题】:How can I test the controller of an Angular directive?如何测试 Angular 指令的控制器?
【发布时间】:2015-12-30 07:40:42
【问题描述】:

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

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

这是我的代码的简化示例:

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 & Karma

【问题讨论】:

    标签: angularjs unit-testing scope controller directive


    【解决方案1】:

    带有简化代码的快速 Plunker 似乎可以工作。 (http://plnkr.co/edit/5kFq3kfbnrdRObapWTx6)。

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

    template: '<div></div>'
    

    ,但这不应该有所作为。因此,您可能无法在测试设置中运行某些东西,或者您在简化示例代码时纠正了自己的错误。

    这可能更有资格发表评论,但没有只发表评论的声誉

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多