title: Angular test using $httpBackend fails with "400 thrown" error
body: <p>For hours I've been trying to test my NewPostController with $httpBackend. The problem is whenever I set non-2xx status code in the response, the test fails.</p>
  
  <p>NewPostController has the following method:</p>
  
  <pre><code>$scope.submit = function () {
    var newPost = $scope.newPost;
      PostService.insertPost(newPost).then(function (post) {
        $location.path("/my-posts");
      }, function (status) {
          $scope.form.$setPristine();
          $scope.error = status;
      });
  };
  </code></pre>
  
  <p>I have a problem testing the failure path:</p>
  
  <pre><code>it(...) {
    ...
    $scope.post.text = "";
    $httpBackend.expectPOST("/create-post", {"post":$scope.post}).respond(400);
    $scope.submit();
    $httpBackend.flush();
    expect($scope.error).toBeDefined();
  
    $scope.post.text = "This is a valid text.";
    $httpBackend.expectPOST("/create-post", {"post": $scope.post}).respond(200);
    $scope.submit();
    $httpBackend.flush();
    expect($location.path()).toBe("/my-posts");
  });
  </code></pre>
  
  <p>The test fails with a message "400 thrown" (no callstack). I tried to change the order of subtests, use whenPOST instead of expectPOST and combine the methods as they do in Angular docs (<a href="https://docs.angularjs.org/api/ngMock/service/" rel="nofollow">https://docs.angularjs.org/api/ngMock/service/</a>$httpBackend) but without success.</p>
  
  <p>Please help.</p>
  
  <p>EDIT:</p>
  
  <p>Now when I look at PostService, it makes sense where the "400 thrown" comes from but I expected the error to be handled by angular. I threw it because of the section "Handling problems in nested service calls" of <a href="http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/" rel="nofollow">this article</a>. It is supposed to be a shorter version of deferred.resolve/reject mechanism.</p>
  
  <pre><code>this.insertPost = function (newPost) {
    return $http({
      method: "post",
      url: "/create-post",
      data: {
        post: newPost
      }
    }).then(function (res) {
        return (res.data);
    }, function (res) {
        throw res.status;
    });
  };
  </code></pre>