3

I know that this error appears in questions a lot but despite my efforts I didn't manage to solve my problem.

I have a Service that fetches some categories from Parse. This is done successfully when running my test but I am getting the error shown in the title.

My code is the following:

ParseService.js

angular.module('starter').service('ParseService', ['$q', function ($q) {

  this.getAllCategories = function() {

    var deferred = $q.defer();

    var categories = [];

    var query = new Parse.Query("Category");

    query.find({

      success: function(results) {

        console.log('Succesfully queried Parse.');

        for (var i = 0; i < results.length; i++) {
          var result = results[i];
          categories.push(result.get("name"));
        }

        deferred.resolve(categories);

        console.log(categories);
      },

      error: function(error) {

        console.log('Error querying Parse.');

        console.log(error);

        deferred.reject(error);
      }

    });

    return deferred.promise;

  };

}]);

ParseServiceTest.js

describe('ParseService', function(){

  var service;

  beforeEach(function(){
    module('starter');
  });

  it ('should fetch Categories', function(done){

    beforeEach(inject(function(ParseService){
      service=ParseService;
    }));

    var promise = service.getAllCategories();

    promise.then(function(categories){
      expect(categories.length).toEqual(5);
      done();
    });

  });

});

Now the console output is the following:

'Succesfully queried Parse.'
['Pets', 'Automobile', 'Social', 'Retail', 'Technology']

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

It seems like the service returns the categories successfully but the done() method is never executed for some reason.

You can ignore the fact that I don't mock the call to Parse. I am aware that this is not the best practice.

1 Answer 1

1

For resolving/rejecting $q promises in tests, you need to start the digest cycle.

describe('ParseService', function() {
  var service;
  var $rootScope;

  beforeEach(module('starter'));

  beforeEach(inject(function(ParseService, _$rootScope_) {
    service = ParseService;
    $rootScope = _$rootScope_;
  }));

  it('should fetch Categories', function(done) {
    var promise = service.getAllCategories();

    promise.then(function(categories) {
      expect(categories.length).toEqual(5);
      done();
    });
    // run digest cycle to resolve $q promises
    $rootScope.$digest();
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.