I have created a service to serve as a client of my backend API. When backend returns an error, my service should handle that problem by rethrowing the error with more readable message to be later caught at controller level:
function readApi() {
return $http.get("adress").catch(function (e) {
if (e.status === 400) {
throw new Error("API call not succeded...");
}
}).then(function (requestResult) {
// further processing of result
});
}
Then, I tried to write a spec in Jasmine testing this behaviour:
it('throw proper error for 400 reponse from API', function () {
httpBackend.expectGET('address').respond(400, '');
expect(function () {
myService.readApi();
}).toThrow();
httpBackend.flush();
});
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
Unfortunately the error seems to be thrown from httpBackend.flush() instead my function, leading to failure of test.
Am using it wrong or is it error in httpBackend mock? How can i perform such test?
EDIT
I tried @tomepejo's answer and it almost worked:
it('throw proper error for 400 reponse from API', function () {
httpBackend.expectGET('address').respond(400, '');
expect(function () {
myService.readApi();
httpBackend.flush();
}).toThrow();
});
afterEach(function () {
//httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
Unfortunately uncomenting afterEach's body leads to error:
Error: [$rootScope:inprog] $digest already in progress
http://errors.angularjs.org/1.3.14/$rootScope/inprog?p0=%24digest
at .../Scripts/Lib/angular.js:63:12
at beginPhase (.../Scripts/Lib/angular.js:14755:15)
at Scope.$digest (.../Scripts/Lib/angular.js:14197:9)
at Function.$httpBackend.verifyNoOutstandingExpectation (.../Scripts/Lib/angular-mocks.js:1550:38)
at Object.<anonymous> (.../ApiClientTest.js:94:29)
I think it doesn't need mentioning, that this afterEach is useful in numerous other tests and pasting those calls at the end on every test (or extracting exception testing to another describe) doesn't feel like a right way to do it.
Or maybe it is a bug in an angular-mocks library and I should file a bug report?