Augustin
Augustin

Reputation: 71

Unit-testing an Angular Controller's initialization function

I am faced with what is I believe a very straightforward scenario, but I cannot find a clear answer: I have a controller which does a number of things when created, including somewhat complicated stuff, and so I have created an initialization function to do it.

Here's what the controller code looks like:

function MyCtrl() {
    function init() {
            // do stuff
    }
    var vm = this;
    vm.init = init;
    vm.init();
}

Obviously, I want to unit test init(), but I cannot find a way to do so: when I instanciate the controller in my tests, init() is run once, which makes it hard to correctly test its side-effects when I run it a second time.

I'm using karma-jasmine for the tests, and usually do something like this:

describe('Controller: MyCtrl', function () {
    var myCtrl;
    beforeEach(angular.mock.module('myApp'));
    beforeEach(inject(function ($controller, $rootScope) {
        $scope = $rootScope.$new();
        createController = function () {
            return $controller('MyCtrl', {$scope: $scope});
        };
    }));
    it('bleh', function() {
        myCtrl = createController();
        // init has already been run at that point
    });
)};

Again, I'm sure it's really straightforward and I'm simply missing the point, but I'm still fairly new to Angular. Thanks a lot for your help!

Upvotes: 3

Views: 1985

Answers (1)

Augustin
Augustin

Reputation: 71

Putting JB Nizet's answer here instead of in a comment.

Many thanks for answering!

It's a chicken and egg problem: init is called by the constructor, and you need to call the constructor in order to call your init function(s). I still maintain that the fact that you have one or several "private" functions called by the constructor is an implementation detail. What you really want to test is that the constructor does its job. You could simplify that by delegating to service functions (that could be unit tested, and mocked when testing the controller).

Upvotes: 2

Related Questions