Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use mock $httpBackend to test error branch

Tags:

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!');
});

});
like image 700
Adi Roiban Avatar asked Jun 16 '13 12:06

Adi Roiban


1 Answers

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...

like image 111
jvandemo Avatar answered Oct 22 '22 13:10

jvandemo