Reputation: 28046
I am trying to test whether or not a particular function was called in my Angular controller.
.controller('demo',function(){
function init(){
//some code..
}
init();
}
My test code looks something like below:
describe(..
beforeEach(...
function createController() { /*call this fn to create controller */
)
describe('controller initilization'.function(){
var spy = spyOn(this,init)
createController();
expect(spy).toHaveBeenCalled();
}
)
ofcourse the above unit test fails. So how would i check if the function init() was called ?
Upvotes: 1
Views: 814
Reputation: 20155
The code you wrote isnt "spy-able". So either dont spy on init or only mock the controller collaborators.
You wrote the equivalent of a private method in Java.So make it public OR make the method belong to a collaborator.
move init into a service,pass the $scope as an argument if needed.
module.service('Init',function(){
this.init=function($scope){};
})
.controller('Ctrl',function($scope,Init){
Init.init($scope);
})
then
$scope=$rootScope.new();
Init=$injector.get('Init');
spyOn(Init,'init');
Ctrl=$controller('Ctrl',{$scope:$scope});
expect(Init.init).toHaveBeenCalledWith($scope);
Upvotes: 1