How to write testable controllers with private methods in AngularJs?

The controller function you provided will be used by Angular as a constructor; at some point it will be called with new to create the actual controller instance. If you really need to have functions in your controller object that are not exposed to the $scope but are available for spying/stubbing/mocking you could attach them to this.

function Ctrl($scope, anyService) {

  $scope.field = "field";
  $scope.whenClicked = function() {
    util();
  };

  this.util = function() {
    anyService.doSmth();
  }
}

When you now call var ctrl = new Ctrl(...) or use the Angular $controller service to retrieve the Ctrl instance, the object returned will contain the util function.

You can see this approach here: http://jsfiddle.net/yianisn/8P9Mv/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)