Question

I would like to inject this function into the ng-init directive when I instantiate a controller in an angular test, in the html I would set it up like this:

 <div ng-controller="my-ctrl" ng-init="initialize({updateUrl: 'list_json'})

In my test I could just write a function like this which would stick the correct stuff in the scope but I think it is messy. Also I am worried about the function currently hard-wired in the html messing it up in my midway test

function initController($scope){

  $scope['updateUrl'] = 'list_json'

}
Was it helpful?

Solution

I don't think that ng-init creates any functions by itself, so I think it's just a wrong way of using it (judged by your snippets).

What I usually do is create the init function myself and then test it without a problem in the controller's unit test.

<div ng-controller="my-ctrl" ng-init="init({ updateUrl : 'list_json' })">...</div>

function MyController($scope){

  $scope.init = function(config) {
     $scope.updateUrl = config.updateUrl;
  }

}

Then in Jasmine you can without a problem write a test which would call the init() function (boilerplate skipped):

// Given
var config = { updateUrl : 'list_json' };
// When
myController.init(config);
// Then
// ...

Important comment about Unit Testing

If you think that you should be testing if your HTML markup is calling init() with given parameters, then I think you are wrong. There is simply nothing to test. There is no logic there at all! Your tests should be verifying that components work how they should work, if programmer will make a mistake with passing wrong parameters from HTML to Angular, then you shouldn't be bothered with covering such mistakes in unit tests. You can't force people not to make mistakes :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top