AngularJS / Karma - Testing function returns a promise that was allowed or rejected

Attempting unit test in karma using AngularMock if my function returned a promise that was rejected, but might not seem surprising at all in this matter.

I have a service like UserService that has a function: processIdentityResponse that returns a promise that is either allowed 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 check that if a forbidden property exists, the rejected promise is returned, and if not, then it is allowed ... how can I achieve this?

I tried something like the following without 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); }); 
+6
source share
2 answers

It seems that the reason is that the promise has not yet been resolved, as it is asynchronous.

Basically you should $rootScope.$digest() after this:

 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); })); 
+6
source

To add to what Dominic said, I used the Jasimine done() asynchronous support function. Think of it as a pause / wait 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 a long request }); it('it should be true',function(done){ promise.catch(function(){ rejected=true}); $rootScope.$digest();//important expect(rejected).toBeTruthy(); done(); }); }); 
+1
source

Source: https://habr.com/ru/post/975828/


All Articles