[英]AngularJS Mock Self Executing Controller
How do I prevent an angular controller with a self instantiating function from executing for tests? 如何防止带有自实例化功能的角度控制器执行测试?
(I have used a contrived example to illustrate my issue) (我用一个人为的例子来说明我的问题)
I have a controller that executes some code on startup (in my case ajax) 我有一个在启动时执行一些代码的控制器(在我的情况下为ajax)
var app = angular.module('app', []);
app.controller('myCtrl', function () {
this.doSomething = function () {
console.log('nahh');
};
this.doSomething();
});
I am attempting to write a test for the controller. 我正在尝试为控制器编写测试。 I don't want doSomething to execute.
我不希望doSomething执行。
var ctrl = $controller('myCtrl',
{
$scope: {}
});
// ctrl.doSomething has already run!
expect(something).to.be(true);
When using backbone.js I would do something like: 当使用bone.js时,我会做类似的事情:
MyCtrl.prototype.doSomething = function(){};
myCtrl = new MyCtrl();
I modify the prototype before initialisation to prevent execution. 我在初始化之前修改了原型以防止执行。 $controller appears to give me an instance of the controller.
$ controller似乎给了我一个控制器实例。 It would be useful to be able to get the prototype.
能够获得原型将很有用。 There may be other ways to overcome this I am not aware of!
我可能不知道还有其他方法可以克服这个问题!
As I mentioned in the comment, I got around this problem by putting my intialisation code in an init
function. 正如我在评论中提到的,我通过将初始化代码放在
init
函数中来解决这个问题。 I then used ng-init
to start this code when it is on the dom. 然后,当它在dom上时,我使用
ng-init
启动此代码。 This allowed me to test the controller in code without it starting itself. 这使我无需启动即可在代码中测试控制器。
JS: JS:
$scope.init = function() {
doSomething();
};
HTML: HTML:
<div ng-controller="myController" ng-init="init()">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.