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!');
});
});
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With