Angular承诺不会在茉莉花中解决

时间:2013-12-01 10:21:50

标签: unit-testing angularjs jasmine promise q

我有以下茉莉花测试:

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();
    });

}));

我认为$ rootScope。$ apply应该解决所有未完成的承诺,但不知何故在这个测试中不会发生。

如何在这样的测试中触发promise解析?请帮忙!

1 个答案:

答案 0 :(得分:12)

我认为$rootScope.$apply()在您的情况下过早被调用。这应该有效:

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

<强>更新

您可以注入mock $timeout service并使用$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();

    // ...