AngularJs - How to write testable controllers with private methods

I am trying to write a test for one of my controllers using angular.js + jasmine.

Say I have a controller

angular.module('app').controller('MyCtrl', function() {
    this.myFunc = function() {
        // ...
    };

    activate();

    function activate() {
        this.myFunc();
    }
});

This controller has a function called activate (), which is called when the controller is created.

How can I write a test for the activate () function? (for example: when creating the controller, it should call the controller function "myFunc ()")

I tried to write something like this:

describe('activate() controller', function() {
    it('should call function myFunc', inject(function($rootScope, $controller) {
        var locals     = {$scope: $rootScope.$new()};
        var controller = $controller('MyCtrl', locals);

        spyOn(controller, 'myFunc').toHaveBeenCalled();
    });
}

But I get the error:

My myFunc is expected to be called.

I think that at the time of creating your spy, the controller already called the activation function.

Is there a way to test the controller this way?

+4
source share
1 answer

myFunc . . , myFunc.

, , , .

+1

All Articles