dbabaioff
dbabaioff

Reputation: 268

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?

Upvotes: 4

Views: 559

Answers (1)

Brandon Brooks
Brandon Brooks

Reputation: 271

The code example you have above executes the myFunc method upon initialization. Therefore, by the time you attach the spy, it has already been executed. The better way of testing would be to inspect what transformations the myFunc has performed.

If the method were part of a service, you could setup your spy in your inject, and then initialize the controller and expect the service method to have been called.

Upvotes: 1

Related Questions