To test the catch
block of a promise in Jasmine for an AngularJS application, you can use the $q
service provided by AngularJS to create and resolve promises in your test specs. The $q
service allows you to control the flow of asynchronous operations and test the behavior of promises, including the catch
block.
Here's an example of how to test the catch
block of a promise using Jasmine and AngularJS:
Suppose you have a service that returns a promise, and you want to test the catch
block in your test spec.
Service code (example service):
javascript// myService.js
angular.module('myApp').factory('myService', function ($http, $q) {
return {
getData: function () {
// Assuming $http.get returns a promise
return $http.get('/api/data').then(
function (response) {
return response.data;
},
function (error) {
// Handle the error in the catch block
return $q.reject(error);
}
);
},
};
});
Test spec:
javascriptdescribe('myService', function () {
var $httpBackend, $rootScope, myService;
// Load the module containing the service
beforeEach(module('myApp'));
// Inject the required services and set up the $httpBackend
beforeEach(inject(function (_$httpBackend_, _$rootScope_, _myService_) {
$httpBackend = _$httpBackend_;
$rootScope = _$rootScope_;
myService = _myService_;
}));
// Test the catch block of the promise
it('should handle error in catch block', function () {
// Mock the $httpBackend response with an error status
$httpBackend.whenGET('/api/data').respond(500, { message: 'Server error' });
// Call the service method that returns the promise
var promise = myService.getData();
// Flush the $httpBackend to initiate the request
$httpBackend.flush();
var errorResponse;
// Register the 'catch' block using 'catch' or 'then' with the second function as the error handler
promise.catch(function (error) {
errorResponse = error;
});
// Flush the $q service's async queue to resolve the promise
$rootScope.$digest();
// Expect that the error was handled correctly
expect(errorResponse.status).toBe(500);
expect(errorResponse.data).toEqual({ message: 'Server error' });
});
});
In this test spec, we have created a mock for the service call using $httpBackend
to return an error response with status code 500. We then call the myService.getData()
method, which returns a promise. We use the catch
method (or alternatively, you can use then
with the second function as the error handler) to handle the error in the catch
block.
After resolving the promise using $rootScope.$digest()
, we expect that the error was properly caught and handled in the catch
block.
By using the $q
service and Jasmine's testing utilities, you can effectively test the catch
block of promises in your AngularJS applications.