Angular promise not resolving in jasmine

梦想与她 提交于 2019-12-01 03:06:01

问题


I have the following jasmine test:

it('should resolve promise', inject(function ($q, $rootScope) {

    function getPromise(){
        var deferred = $q.defer();
        setTimeout(function(){
            deferred.resolve(true);
        }, 1000);
        return deferred.promise;
    }

    var p = getPromise();
    var cb = jasmine.createSpy();

    runs(function(){
        expect(cb).not.toHaveBeenCalled();

        p.then(cb);

        $rootScope.$apply();
    });

    waitsFor(function(){
        return cb.callCount == 1;
    });

    runs(function(){
        expect(cb).toHaveBeenCalled();

        $rootScope.$apply();
    });

}));

I thought $rootScope.$apply was supposed to resolve all outstanding promises, but somehow it does not happen in this test.

How do i trigger promise resolving in a test like this? please help!


回答1:


I think the $rootScope.$apply() is being called too soon in your case. This should work:

function getPromise(){
    var deferred = $q.defer();
    setTimeout(function(){
        deferred.resolve(true);
        $rootScope.$apply();
    }, 1000);
    return deferred.promise;
}

Update

You can inject mock $timeout service and resolve the promise in that explicitly using $timeout.flush().

it('should resolve promise', inject(function ($q, $timeout, $rootScope) {

    function getPromise(){
        var deferred = $q.defer();
        $timeout(function(){
            deferred.resolve(true);
        }, 1000); 
        return deferred.promise;
    }

    // ...

    $timeout.flush();

    // ...


来源:https://stackoverflow.com/questions/20311118/angular-promise-not-resolving-in-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!