2achary 2achary - 4 months ago 27
AngularJS Question

AngularJS $q.defer() with jasmine done(): promise.then function not getting called

Can someone help me understand why this isn't working? I'm using Jasmine's

both
function to wait for the promise.then function too be called and make an assertion. But it times out before it is called.

describe('greeting', function(){
var greeting = 'hello';

it('should call promise.then', function(done) {
inject(function ($q) {
var deferred = $q.defer();
deferred.resolve(greeting);

deferred.promise.then(function (greeting) {
expect(greeting).toEqual('hello');
done();
});

});
});
});


The
then
function doesn't get called and Jasmine times out with this message:

Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

Answer

Make sure you do a $scope.$apply to trigger the angular digest cycle, like this:

inject(function ($q, $rootScope) {
   var deferred = $q.defer();
   deferred.resolve(greeting);

   deferred.promise.then(function (greeting) {
      expect(greeting).toEqual('hello');
      done();
   });
   $rootScope.$apply();
});

Should fix the issue

Comments