AngularJS: how do I use an angular service during module configuration time?

See this plunkr for a live example: http://plnkr.co/edit/djQPW7g4HIuxDIm4K8RC

In the code below, the line var promise = serviceThatReturnsPromise(); is run during module configuration time, but I want to mock out the promise that is returned by the service.

Ideally I'd use the $q service to create the mock promise, but I can't do that because serviceThatReturnsPromise() is executed during module configuration time, before I can get access to $q. What's the best way to resolve this chicken and egg problem?

var app = angular.module('plunker', []);

app.factory('serviceUnderTest', function (serviceThatReturnsPromise) {
  // We mock out serviceThatReturnsPromise in the test
  var promise = serviceThatReturnsPromise();
  return function() {
    return 4;
  };
});

describe('Mocking a promise', function() {
  var deferredForMock, service;

  beforeEach(module('plunker'));

  beforeEach(module(function($provide) {
    $provide.factory('serviceThatReturnsPromise', function() {

        return function() {
          // deferredForMock will be undefined because this is called
          // when `serviceUnderTest` is $invoked (i.e. at module configuration),
          // but we don't define deferredForMock until the inject() below because  
          // we need the $q service to create it. How to solve this chicken and
          // egg problem?
          return deferredForMock.promise;
        }
    });
  }));

  beforeEach(inject(function($q, serviceUnderTest) {
    service = serviceUnderTest;
    deferredForMock = $q.defer();
  }));

  it('This test won\'t even run', function() {
    // we won't even get here because the serviceUnderTest
    // service will fail during module configuration
    expect(service()).toBe(4);
  });
});

I'm not sure I like the solution much, but here it is:

http://plnkr.co/edit/uBwsJxJRjS1qqsKIx5j7?p=preview

You need to ensure that you don't instantiate "serviceUnderTest" until after you've set-up everything. Therefore, I've split the second beforeEach into two separate pieces: the first instantiates and uses $q, the second instantiates and uses serviceUnderTest.

I've also had to include the $rootScope, because Angular's promises are designed to work within a $apply() method.

Hope that helps.