mercredi 6 mai 2015

AngularJs - How to write testable controllers with private Methods

I'm trying to write a test for one of my controller, using angular.js + jasmine.

Let's say I have a controller

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

    activate();

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

This controller have a function called activate() that is called when the controller is created.

How can I write a test for the activate() function? (like this: when the controller is created, should call a 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: Expected spy myFunc to have been called. I think at the point I create my spy, the controller already called the activate function.

Is there a way to test a controller like this?

Aucun commentaire:

Enregistrer un commentaire