title: Mock angular factory that uses $q in Jasmine
body: <p>Surely this has been asked before but I can't find it. I need to mock a factory, but the mock itself needs to use $q, and I end up in a chicken and egg situation with regards to calling module() after inject().</p>
  
  <p>I looked at this <a href="https://stackoverflow.com/questions/23705051/how-do-i-mock-a-service-that-returns-promise-in-angularjs-jasmine-unit-test">question</a> which advises doing a spyOn, which works for <strong>services</strong> because it is a singleton, but I am calling <strong>new</strong> on the function returned by my factory, creating a new instance each time, so that won't work...</p>
  
  <pre><code>var app = angular.module('app', []);
  
  app.factory('MyDependencyFactory', function() {
    return function() {
      this.doPromise = function () {
        var defer = $q.defer();
        //obviously more complicated.
        defer.resolve();
        return defer.promise;   
      }
    }
  });
  
  app.factory('MyConsumingFactory', function(MyDependencyFactory) {
   return function() {
     var dependency = new MyDependencyFactory();
     this.result;
  
     this.doSomething = function () {
       dependency.doPromise().then(
         function (data) {
           this.result = data;
         },
         function (error) {
           console.log(error);
         }
         );
     }
    }
  });
  </code></pre>
  
  <p>Jasmine test:  </p>
  
  <pre><code>describe('MyConsumingFactory', function() {
    var MyConsumingFactory;
  
    beforeEach(function () {
      module('app');
  
      inject( function (_MyConsumingFactory_) {
        MyConsumingFactory = _MyConsumingFactory_;
      });
  
      inject( function ($q) {
        mockMyDependencyFactory = function () {
          this.doPromise = function (data) {
              var defer = $q.defer();
              defer.resolve('mock data');
            };
          };
      });
  
      module( function ($provide) {
        $provide.factory('MyDependencyFactory', mockMyDependencyFactory);
      });
    });
  
    it('works correctly', function () {
      MyConsumingFactory.doSomething();
      $rootScope.$apply();
      expect(MyConsumingFactory.result).toEqual('mock data');
    });
  
  });
  </code></pre>
  
  <p>I need my mockMyDependencyFactory to use $q, so I need to wrap it in <strong>inject( function(...</strong>, and I need to do this before the call to <strong>module( function ($provide) {...</strong> which of course give me:</p>
  
  <p><strong>Error: Injector already created, can not register a module!</strong></p>
  
  <p>Any suggestions on how I get round this?</p>
  
  <p>Or if you think my design flawed (I suppose I could instantiate a MyDependencyFactory and pass that during instantiation of MyConsumingFactory instead of using angular's DI?) I'm all ears :)</p>