title: How to unit test an angularjs promise chain using $httpBackend
body: <p>Using AngularJS, I am trying to unit test a function that makes multiple calls to $http.</p>
  
  <p>My test looks something like this:</p>
  
  <pre><code>it('traverses over a hierarchical structure over multiple chained calls', function() {
  
      myService.traverseTheStuff()
      .then(function(theAggregateResult) {
          // ...is never fulfilled
      });
  
      $httpBackend.flush();
  });
  </code></pre>
  
  <p>Other single-call tests will register the callback passed to .then() and execute it as soon as I call .flush().</p>
  
  <p>The code under test looks something like this.</p>
  
  <pre><code>function traverseTheStuff(){
  
      // This will make a call to $http to fetch some data
      return getRootData()
  
      // It is fulfilled at the end of the test when I $httpBackend.flush()
      .then(function(rootData){
  
          // Another call to $http happens AFTER $httpBackend.flush()
          return getNextLevel(rootData.someReference);
      })
  
      // The second promise is never fulfilled and the test fails
      .then(function(nextLevel){
          return aggregateTheStuff(...);
      });
  }
  </code></pre>
  
  <p>For what its worth, each of the single calls is unit tested separately. Here, I want to traverse a tree, aggregate some data and unit test a) that the promise chaining is hooked up correctly and b) the aggregation is accurate. Flattening it out into separate discrete calls is already done.</p>