当单元测试如何注入控制器进入指令 [英] How to inject a controller into a directive when unit-testing
问题描述
我想测试一个AngularJS指令声明如下
app.directive('myCustomer',函数(){
返回{
模板:cust.html
控制器:'customerController
};
});
在测试中,我想注入(或重写)控制器,这样我可以测试只是指令(例如模板)的其他部分。在 customerController
当然可以单独测试。这样,我得到一个测试的完全分离。
- 我曾尝试通过在测试设置控制器属性重写控制器。
- 我试图注入
customController
使用$提供
。 - 我已经尝试设置
NG-控制器
在测试中使用的HTML指令申报。
我不能得到任何这些工作。这个问题似乎是,我不能让一个参考的指令,直到我有 $编译
D吧。但是编译之后,控制器已经设置了。
VAR元素= $编译(<我的客户的>< /我的客户的>)($ rootScope);
我觉得这是一个比接受的答案,这并不需要创建一个新的模块,简单的方法。
努力,当你接近 $提供
,但嘲讽的控制器,可以使用不同的东西: $ controllerProvider
。使用寄存器()
法在规范模拟出你的控制器。
beforeEach(模块('对myApp',函数($ controllerProvider){
$ controllerProvider.register('customerContoller',函数($范围){
//模拟控制器
});
});
I want to test an AngularJS directive declared like this
app.directive('myCustomer', function() {
return {
template: 'cust.html'
controller: '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.
- 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.
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 $compile
d 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.
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屋!