I'm currently working on writing a test for one of my controllers using angular.js and jasmine.
Imagine I have a controller defined as follows:
angular.module('app').controller('MyCtrl', function() {
this.myFunc = function() {
// ...
};
activate();
function activate() {
this.myFunc();
}
});
This controller contains a function called activate() which gets triggered when the controller is initialized.
Now, I am trying to figure out how to effectively test the activate() function. Essentially, I want to ensure that when the controller is created, it calls the function "myFunc()".
Here's an approach I've tried:
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();
});
}
However, I encountered the following error:
Expected spy myFunc to have been called.
It seems like by the time I create the spy, the activate function has already been called by the controller.
Does anyone know of a way to properly test a controller in this scenario?