title: Testing AngularUI Bootstrap modal instance controller
body: <p>This is a somewhat of a follow-on question to this one: <a href="https://stackoverflow.com/q/21214868/736963">Mocking $modal in AngularJS unit tests</a></p>
  
  <p>The referenced SO is an excellent question with very useful answer. The question I am left with after this however is this: how do I unit test the modal instance controller? In the referenced SO, the invoking controller is tested, but the modal instance controller is mocked. Arguably the latter should also be tested, but this has proven to be very tricky. Here's why:</p>
  
  <p>I'll copy the same example from the referenced SO here:</p>
  
  <pre><code>.controller('ModalInstanceCtrl', function($scope, $modalInstance, items){
    $scope.items = items;
    $scope.selected = {
      item: $scope.items[0]
    };
  
    $scope.ok = function () {
      $modalInstance.close($scope.selected.item);
    };
  
    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  });
  </code></pre>
  
  <p>So my first thought was that I would just instantiate the controller directly in a test, just like any other controller under test:</p>
  
  <pre><code>beforeEach(inject(function($rootScope) {
    scope = $rootScope.$new();
    ctrl = $controller('ModalInstanceCtrl', {$scope: scope});
  });
  </code></pre>
  
  <p>This does not work because in this context, angular does not have a provider to inject $modalInstance, since that is supplied by the UI modal.</p>
  
  <p>Next, I turn to plan B: use $modal.open to instantiate the controller. This will run as expected:</p>
  
  <pre><code>beforeEach(inject(function($rootScope, $modal) {
    scope = $rootScope.$new();
    modalInstance = $modal.open({
      template: '&lt;html&gt;&lt;/html&gt;',
      controller: 'ModalInstanceCtrl',
      scope: scope
    });
  });
  </code></pre>
  
  <p>(Note, template can't be an empty string or it will fail cryptically.)</p>
  
  <p>The problem now is that I have no visibility into the scope, which is the customary way to unit test resource gathering, etc. In my real code, the controller calls a resource service to populate a list of choices; my attempt to test this sets an expectGet to satisfy the service my controller is using, and I want to validate that the controller is putting the result in its scope. But the modal is creating a <em>new</em> scope for the modal instance controller (using the scope I pass in as a prototype), and I can't figure out how I can get a hole of that scope. The modalInstance object does not have a window into the controller.</p>
  
  <p>Any suggestions on the "right" way to test this?</p>
  
  <p>(N.B.: the behavior of creating a derivative scope for the modal instance controller is not unexpected – it is documented behavior. My question of how to test it is still valid regardless.)</p>