I'm trying to test that my program processes the error messages I get from http requests properly, but I can't figure out how to mock that with $httpBackend. Given the following:
$httpBackend.expectGET(path).respond(400, object);
400 sets response.status, and object sets response.data, but how do I set response.error? The data I need to test isn't in the data field.
Example API response:
{
status: 400,
data: {},
error: {}
}
the code ...
$httpBackend.expectGET(path).respond(400, object);
is saying when the code makes a request to the 'path' endpoint, respond with 400 status code with the response 'object'
so, for example, lets say that your unit test hits this code in your app ...
$http.GET(path).then(function(response) {
// this code is hit with 2xx responses
vm.fred = 'hello';
}).catch(function(errorResponse) {
// this code is hit with any status code not starting with 2! e.g. 400
vm.fred='failed';
});
Thus your code will cause the catch block to be executed. However, inside your unit test, to force the execution of the catch block you will need to do ...
$rootScope.$digest();
this will trigger the execution of the then or catch blocks (whichever is relevant).
you can then make expectations in your unit test as usual. Note that in your example errorResponse will be object.
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