角承诺在茉莉没有解决 [英] Angular promise not resolving in jasmine

查看:219
本文介绍了角承诺在茉莉没有解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下茉莉测试:

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。$申请应该解决所有悬而未决的承诺,但不知何故,没有在这个测试中发生的。

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!

推荐答案

我觉得 $ rootScope。$适用()被调用你的情况还为时过早。这应该工作:

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

更新

您可以注入模拟 $超时服务和解决的承诺,明确使用 $ 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();

    // ...

这篇关于角承诺在茉莉没有解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆