【问题标题】:How to inject a controller into a directive when unit-testing单元测试时如何将控制器注入指令
【发布时间】:2014-02-08 16:40:00
【问题描述】:

我想测试一个像这样声明的 AngularJS 指令

app.directive('myCustomer', function() {
    return {
      template: 'cust.html'
      controller: 'customerController'
    };
  });

在测试中,我想注入(或覆盖)控制器,这样我就可以只测试指令的其他部分(例如模板)。 customerController 当然可以单独测试。这样我就可以清楚地分离测试。

  • 我尝试通过在测试中设置控制器属性来覆盖控制器。
  • 我尝试使用$provide 注入customController
  • 我已尝试在测试中使用的 html 指令声明上设置 ng-controller

我无法让其中任何一个工作。问题似乎是在我拥有$compiled 之前我无法获得对该指令的引用。但是编译后,控制器已经设置好了。

 var element = $compile("<my-customer></my-customer>")($rootScope);

【问题讨论】:

  • 能否请您展示您的规范和您尝试过的代码?

标签: angularjs unit-testing dependency-injection controller directive


【解决方案1】:

一种方法是定义一个新模块(例如“specApp”),将您的应用(例如“myApp”)声明为依赖项。然后使用“specApp”模块注册一个“customerController”控制器。这将有效地“隐藏”“myApp”的 customerController,并在编译时将此模拟控制器提供给指令。
例如:

您的应用

var app = angular.module('myApp', []);
...
app.controller('customerController', function ($scope,...) {
    $scope = {...};
    ...
});
app.directive('myCustomer', function () {
    return {
        template: 'cust.html',
        controller: 'customerController'
    };
});

您的规格

describe('"myCustomer" directive', function () {
    $compile;
    $newScope;

    angular.module('specApp', ['myApp'])
    /* Register a "new" customerController, which will "hide" that of 'myApp' */
    .controller('customerController', function ($scope,...) {
        $scope = {...};
        ...
    });

    beforeEach(module('specApp'));

    it('should do cool stuff', function () {
        var elem = angular.element('<div my-customer></div>');
        $compile(elem)($newScope);
        $newScope.$digest();
        expect(...
    });
});

另请参阅此working demo

【讨论】:

    【解决方案2】:

    我认为有一种比接受的答案更简单的方法,不需要创建新模块。

    您在尝试 $provide 时很接近,但对于模拟控制器,您使用了不同的东西:$controllerProvider。在您的规范中使用register() 方法来模拟您的控制器。

    beforeEach(module('myApp', function($controllerProvider) {
        $controllerProvider.register('customerContoller', function($scope) {
            // Controller Mock
        });
    });
    

    【讨论】:

    • +1 虽然我的回答是一个可行的选择,但这种方法要好得多。 (那是一年多前的事了;我的 ng-fu 很蹩脚 :))如果有人想看看 @fiznool 的做法,这里是 demo
    猜你喜欢
    • 1970-01-01
    • 2016-01-26
    • 2014-02-06
    • 1970-01-01
    • 2012-05-20
    • 2014-09-28
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    相关资源
    最近更新 更多