Testing Angular $ q qith Jasmine 2 and Karma

Trying to test a promise-based service that does something like this:

load : function(){
        var deferred = $q.defer();

        //Do misc async stuff
        deferred.resolve();

        return deferred.promise;
    }

When trying to test this in Karma + Jasmine 2.0, I try to use my callbacks (), but it always runs out of time and does not resolve the promise.

beforeEach(inject(function ($injector) {
    service = $injector.get('myService');
    $window = $injector.get("$window");
    $rootScope = $injector.get('$rootScope');
}));

describe('Call load', function () {
    it('resolves its promise', function (done) {
      service.load().then(function(){
          expect(something).not.toBe(undefined);
          done();
      });
    });
});

From Jasmines docs, this is how I am, although you should use done () along with asynchronous code, but the problem seems to be that the promise never solves

+4
source share
1 answer

As mentioned in the comments of @TimCastelijns, you need to call $scope.$applyto enable promises in your unit tests:

load: function(){
    var deferred = $q.defer();

    setTimeout(function () {
        //Do misc async stuff
        deferred.resolve();
        $rootScope.$apply();
    });

    return deferred.promise;
}
0
source

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


All Articles