1

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 ?

6
  • you can't, you need to make the init function public so it can be tested Commented Jun 19, 2014 at 15:33
  • so i should define it as scope.init ? Commented Jun 19, 2014 at 15:35
  • There should be no $scope when testing, unless you are writing E2E tests... Commented Jun 19, 2014 at 15:36
  • you can do either $scope or just this.init Commented Jun 19, 2014 at 15:38
  • Have a look at this answer: stackoverflow.com/questions/14921602/… Commented Jun 19, 2014 at 15:45

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.