Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $httpBackend how to mock an error response?

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: {}
}
like image 888
TiggerToo Avatar asked Mar 30 '16 16:03

TiggerToo


1 Answers

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.

like image 59
danday74 Avatar answered Sep 20 '22 09:09

danday74