Question: In my Angular application, I have a `controller` defined as follows:

```
angular.module('myApp.controllers')
  .controller('AppController', function($rootScope, $scope, CheckResource) {
    $scope.check = function(data) {
      var promise = CheckResource.query(data).$promise;
      promise.then(function(result) {
         $scope.value = result;
      }, function() {
         $scope.value = "default";
      });
    };
  };

```

And my `CheckResource` is a `Factory` as follows:

```
angular.module('myApp.services', ['ngResource'])
  .factory('CheckResource', function($resource) {
    return $resource('/check', {}, {
      query: {
        method: 'POST'
      }
    });
  });

```

I would like to write a unit test for my controller `AppController` and somehow mock my factory `CheckResource`, but I'm not sure how exactly I can achieve this using `$q` and deferred promise. Can anyone please explain me what's going on this scenario? 

What are my options for testing this scenario? Should I mock my service? Should I use `spyOn`? Should I use `$httpBackend`? Or, should I do an E2E test?

Answer: 
Assuming you have a controller mocked in your test, you can do something like:

```
var deferred;

beforeEach(inject(function($q) {
    deferred = $q.defer();

    myController.CheckResource = {
        query: function() {
            return {$promise: deferred.promise};
        }
    };
}));

```

Then in your test itself:

```
it('tests CheckResource', function() {
     deferred.resolve([]);
     expect(something).toHaveHappened();
});

```
ngResource is defined in the separate module. Please check the documentation <http://docs.angularjs.org/api/ngResource> In other words you have to include and add ngResource dependency to MyApp.Factory module - angular.module("MyApp.Factory", ["ngResource"])

```
var factory;

beforeEach(function () {

  module("MyApp.Factory");

  inject(function (_factory_) {
    factory = _factory_;
  });

});

```