I have a similar service setup:
app.service('usersService.v2', ['$http', '$q', '$exceptionHandler', 'User', 'userValidator.v2', 'CRUD', function($http, $q, $exceptionHandler, User, userValidator, CRUD){
function dummyPromise(){
var dummyDeferred = $q.defer();
dummyDeferred.resolve('dummy');
return deferred.promise;
}
this.getUser = function(userID, companyID){
try{
userValidator.validateId(userID);
userValidator.validateId(companyID);
}
catch(e){
$exceptionHandler(e);
return dummyPromise();
}
return $http.get(apiUrl + 'api/v2/companies/' + companyID + '/users/' + userID)
.then(function(response){
var user = new User(response.data);
try{
userValidator.validateUser(CRUD.READ, user);
}
catch(e){
$exceptionHandler(e);
return;
}
return user;
})
};
}]);
I'm interested in testing the service's behavior based on the validation functions performed by userValidator.*
. These functions contain if/else blocks that throw errors.
In Karma, my test script looks like this:
describe('Service: usersService.v2', function () {
var usersService, httpBackend, state, userValidator;
const url = 'address'
function _inject() {
angular.mock.inject(function ($injector) {
usersService = $injector.get('usersService.v2');
userValidator = $injector.get('userValidator.v2');
httpBackend = $injector.get('$httpBackend');
});
}
beforeEach(function () {
angular.mock.module('app');
_inject();
});
describe('getUser', function () {
beforeEach(function () {
httpBackend.when('GET', url);
});
afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should return a dummy promise if ID validation fails', function(){
spyOn(userValidator, 'validateId').and.throwError('Missing or incorrect ID');
usersService.getUser()
.then(function(data){expect(data).toBe('dummy');})
});
);
})
However, when I run the tests with Karma, an error occurs. It seems like the catch
block used to handle exceptions is not executing properly. What could be the issue here?
Thanks, Manuel
UPDATE: The validate methods look something like this:
... code code code ...
this.validateId = function(ID){
if(!ID || !angular.isNumber(ID)) throw 'Missing or incorrect ID';
}
The problem arises because Karma is attempting to handle the error thrown by validation itself instead of allowing the userService
to manage it.