茉莉花中没有解决的角承诺 [英] Angular promise not resolving in jasmine
本文介绍了茉莉花中没有解决的角承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下茉莉花测试:
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 应该解决所有未完成的承诺,但不知何故,它在这个测试中没有发生.
I thought $rootScope.$apply was supposed to resolve all outstanding promises, but somehow it does not happen in this test.
如何在这样的测试中触发 Promise 解析?请帮忙!
How do i trigger promise resolving in a test like this? please help!
推荐答案
我认为 $rootScope.$apply()
在你的情况下被调用得太早了.这应该有效:
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
服务 并解决其中的承诺显式使用 $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屋!
查看全文