Trying to unit test in Karma with AngularMock if my function has returned a promise that was rejected but can't seem to find ANYTHING surprisingly on the matter.
I have a service like UserService, which has a function: processIdentityResponse
which returns a promise that is either resolved or rejected depending on the logic inside:
processIdentityResponse: function(response)
{
var deferred = $q.defer();
if (response.data.banned) {
deferred.reject(response);
} else {
deferred.resolve(response);
}
return deferred.promise;
}
I want to test that if the banned property exists then a rejected promise is returned and if not, that it is resolved... how can I achieve this?
I tried something like the following to no success:
it('should return a rejected promise if status is a string', function() {
var rejected = false;
UserService.processIdentityResponse(data).catch(function() {
rejected = true;
});
expect(rejected).toBe(true);
});
It seems like the reason is because the promise wasn't yet resolved as it's asynchronous functionality.
You basically have to $rootScope.$digest()
afterwards like so:
it('should return a rejected promise if status is a string', inject(function($rootScope) {
var rejected = false;
UserService.processIdentityResponse(data).catch(function() {
rejected = true;
});
$rootScope.$digest();
expect(rejected).toBe(true);
}));
To add to what Dominic said, I used Jasimine done()
Asynchronous Support function. Think of it as a pause/waiting function.
describe('my description',function(){
beforeEach(function(done){
var rejected = true;
var promise = UserService.processIdentityResponse(data);//add ur service or function that will return a promise here
setTimeout(function(){done();},1500);//set time to 1500ms or more if it's a long request
});
it('it should be true',function(done){
promise.catch(function(){ rejected=true});
$rootScope.$digest();//important
expect(rejected).toBeTruthy();
done();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With