单元测试时如何将控制器注入指令 [英] How to inject a controller into a directive when unit-testing

查看:19
本文介绍了单元测试时如何将控制器注入指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to test an AngularJS directive declared like this

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

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

In the test I would like to inject (or override) the controller, so that I can test just the other parts of the directive (e.g. the template). The customerController can of course be tested separately. This way I get a clean separation of tests.

  • 我尝试通过在测试中设置控制器属性来覆盖控制器.
  • 我尝试使用 $provide 注入 customController.
  • 我尝试在测试中使用的 html 指令声明上设置 ng-controller.
  • I have tried overriding the controller by setting the controller property in the test.
  • I have tried injecting the customController using $provide.
  • I have tried setting ng-controller on the html directive declaration used in the test.

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

I couldn't get any of those to work. The problem seems to be that I cannot get a reference to the directive until I have $compiled it. But after compilation, the controller is already set up.

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

推荐答案

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

I think there is a simpler way than the accepted answer, which doesn't require creating a new module.

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

You were close when trying $provide, but for mocking controllers, you use something different: $controllerProvider. Use the register() method in your spec to mock out your controller.

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

这篇关于单元测试时如何将控制器注入指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆