Snippet of my controller's initialization process:
var initialize = function () {
httpUsers.fetchUsers().then(function (data) {
$timeout(function() {
// Perform some actions...
});
}).catch(function (error) {
vm.error = "Oops!";
toastr.error(error);
});
}
Mocked service for testing purposes:
beforeEach(function() {
module('httpService', function($provide) {
$provide.factory('httpUsers', function () {
var service = {
fetchUsers: fetchUsers
}
function fetchUsers() {
deferred = $q.defer();
deferred.resolve([
{ id: 1, firstName: "John", lastName: "Doe" },
{ id: 2, firstName: "Jane", lastName: "Doe" },
{ id: 3, firstName: "Jack", lastName: "Doe" }
]);
return deferred.promise;
};
return service;
});
});
});
Everything is working smoothly with the resolved promise.
I am now looking to test the catch
scenario in my controller's initialization method.
This is what I have tried:
describe('initialize', function() {
it('should handle error properly', function () {
deferred.reject('sample error');
expect(controller.error).toBe("Uh oh!");
});
});
However, the output received is:
Expected undefined to be 'Uh oh!'.
Neither 'sample error', nor 'Oops!', nor 'Uh oh!' are displayed. How can I forcefully trigger a rejection on the promise during testing?
Thank you!
Additional Information
Here is how my controller is injected:
beforeEach(inject(function(_$controller_, _$rootScope_, _$q_, _$timeout_, _global_) {
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$q = _$q_;
$timeout = _$timeout_;
global = _global_;
controller = _$controller_('usersController', {
$rootScope: $rootScope,
$scope: $scope,
$q: $q
});
$timeout.flush();
}));