How to use mock $httpBackend to test error branch

All we need is an easy explanation of the problem, so here it is.

I am following the AngularJS documentation from here

The problem is that the documentation describes only the “success/happy” branch of the code, and there is no example of how to test the “failure” branch.

What I want to do, is to set the precondition for triggering the $scope.status = 'ERROR!' code.

Here is a minimal example.

// controller
function MyController($scope, $http) {

  this.saveMessage = function(message) {
    $scope.status = 'Saving...';
    $http.post('/add-msg.py', message).success(function(response) {
      $scope.status = '';
    }).error(function() {
      $scope.status = 'ERROR!';
    });
  };
}

// testing controller
var $httpBackend;

beforeEach(inject(function($injector) {
  $httpBackend = $injector.get('$httpBackend');
}));

it('should send msg to server', function() {

  $httpBackend.expectPOST('/add-msg.py', 'message content').respond(500, '');

  var controller = scope.$new(MyController);
  $httpBackend.flush();
  controller.saveMessage('message content');
  $httpBackend.flush();

  // Here is the question: How to set $httpBackend.expectPOST to trigger
  // this condition.
  expect(scope.status).toBe('ERROR!');
});

});

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You are checking a property of the controller while you are setting a property of the scope.

If you want to test for controller.status in your expect call, you should set this.status inside your controller instead of $scope.status.

On the other hand, if you set $scope.status in your controller, then you should use scope.status instead of controller.status in your expect call.


UPDATE: I created a working version for you on Plunker:

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

All tests are passing now…

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply