Question

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)

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.

var ctrl = $controller('myCtrl',
{
    $scope: {}
});
// ctrl.doSomething has already run!

expect(something).to.be(true);

When using backbone.js I would do something like:

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. It would be useful to be able to get the prototype. There may be other ways to overcome this I am not aware of!

Was it helpful?

Solution

As I mentioned in the comment, I got around this problem by putting my intialisation code in an init function. I then used ng-init to start this code when it is on the dom. This allowed me to test the controller in code without it starting itself.

JS:

$scope.init = function() {
  doSomething();
};

HTML:

<div ng-controller="myController" ng-init="init()">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top