Angular promise not resolving in jasmine

后端 未结 1 1060
执念已碎
执念已碎 2021-01-12 18:47

I have the following jasmine test:

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

    function getPromise(){
        var deferred = $q.de         


        
相关标签:
1条回答
  • 2021-01-12 19:47

    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();
    
        // ...
    
    0 讨论(0)
提交回复
热议问题