title: Unit-testing an Angular Controller's initialization function
body: <p>I am faced with what is I believe a very straightforward scenario, but I cannot find a clear answer: I have a controller which does a number of things when created, including somewhat complicated stuff, and so I have created an initialization function to do it.</p>
  
  <p>Here's what the controller code looks like:</p>
  
  <pre><code>function MyCtrl() {
      function init() {
              // do stuff
      }
      var vm = this;
      vm.init = init;
      vm.init();
  }
  </code></pre>
  
  <p>Obviously, I want to unit test init(), but I cannot find a way to do so: when I instanciate the controller in my tests, init() is run once, which makes it hard to correctly test its side-effects when I run it a second time.</p>
  
  <p>I'm using karma-jasmine for the tests, and usually do something like this:</p>
  
  <pre><code>describe('Controller: MyCtrl', function () {
      var myCtrl;
      beforeEach(angular.mock.module('myApp'));
      beforeEach(inject(function ($controller, $rootScope) {
          $scope = $rootScope.$new();
          createController = function () {
              return $controller('MyCtrl', {$scope: $scope});
          };
      }));
      it('bleh', function() {
          myCtrl = createController();
          // init has already been run at that point
      });
  )};
  </code></pre>
  
  <p>Again, I'm sure it's really straightforward and I'm simply missing the point, but I'm still fairly new to Angular. Thanks a lot for your help!</p>