Friday, 15 January 2010

angularjs - Testing functions inside controllers in angular -



angularjs - Testing functions inside controllers in angular -

i trying test whether or not particular function called in angular controller.

.controller('demo',function(){ function init(){ //some code.. } init(); }

my test code looks below:

describe(.. beforeeach(... function createcontroller() { /*call fn create controller */ ) describe('controller initilization'.function(){ var spy = spyon(this,init) createcontroller(); expect(spy).tohavebeencalled(); } )

ofcourse above unit test fails. how check if function init() called ?

the code wrote isnt "spy-able". either dont spy on init or mock controller collaborators.

you wrote equivalent of private method in java.so create public or create method belong collaborator.

move init service,pass $scope 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);

angularjs jasmine

No comments:

Post a Comment