Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS/Karma - Testing function returns promise that has been resolved or rejected

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);
});
like image 750
Intellix Avatar asked Sep 25 '14 11:09

Intellix


2 Answers

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);
}));
like image 131
Intellix Avatar answered Sep 28 '22 07:09

Intellix


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();
 });
});
like image 25
fredtma Avatar answered Sep 28 '22 07:09

fredtma