title: Testing AngularJS controllers with resource services
body: <p><strong>Background:</strong>
  I'm writing unit test for angular js controllers, which utilize angular $resources wrapped in services (for maintainability purposes).</p>
  
  <p><strong>Example controller:</strong></p>
  
  <pre><code>name = 'app.controllers.UsersIndexCtrl'
  angular.module(name, [])
  .controller(name, [
    '$scope'
    '$location'
    '$dialog'
    'Users'
    'UserRoles'
    ($scope, $location, $dialog, Users, UserRoles) -&gt;
      # Get users list
      $scope.users  = Users.query()
  
      # rest...
  
  ])
  </code></pre>
  
  <p><strong>Example resource service:</strong></p>
  
  <pre><code>angular.module('app.services.Users', [])
  .factory 'Users', ['$rootScope', '$http', '$resource', '$location' , ($rootScope, $http, $resource, $location)-&gt;
    baseUrl = '/users'
    Users = $resource baseUrl + '/:userId', {userId: '@_id'}
  
    Users.getStatus = -&gt;
      console.log 'User::getStatus()'
      req = $http.get baseUrl + '/status'
      req.success (res)-&gt; 
        $rootScope.globalUserAccountSettings = res
        unless $rootScope.$$phase then $rootScope.$apply()
  
    # other, custom methods go here...
  ])
  </code></pre>
  
  <p>Most of unit test examples in angular suggest using $httpBackend and thus mocking the $http service in controllers. To be honest, I doubt if it's a good practice since if did so I'd have to hardcode request paths in all controller tests and I want to isolate unit behaviour. $httpBackend mock is really great but only if you are using $resource in controllers directly.</p>
  
  <p><strong>A typical single test using $httpBackend would look like:</strong></p>
  
  <pre><code>it 'should be able to add a new empty user profile', -&gt;
    $httpBackend.flush()
    l = $scope.users.length
    $httpBackend.expect('POST', '/users').respond _.cloneDeep mockResponseOK[0]
    $scope.add()
    $httpBackend.flush()
    expect($scope.users.length).toEqual l + 1
  </code></pre>
  
  <p>What if I created a mock User resource class instance, something like:</p>
  
  <pre><code>angular.module('app.services.Users', [])
  .factory 'Users', -&gt;
    class Users
      $save:(cb)-&gt;
      $remove:-&gt;
      @query:-&gt;
      @get:-&gt;
  </code></pre>
  
  <p>Angular <a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="nofollow">DI</a> mechanisms will override old 'app.services.Users' module with this one in a transparent way and enable me to run checks with jasmine spies.</p>
  
  <p><strong>What bothers me is the fact that I wasn't able to find a <em>single</em> example supporting my idea. So the question is, which one would you use and why or what am I doing wrong?</strong></p>