[英]Jasmine async test using promises
我正在使用角度承諾進行一些Jasmine測試,並且有一個與計時有關的問題。 在Angular中找到了基於單元測試基於承諾的代碼的答案,但需要對其工作方式進行澄清。 鑒於then
方法始終以異步方式處理,如何保證以下測試能夠通過。 是否存在expect
將在被執行的then
塊之前運行並在分配值之前運行期望的風險。 或者...摘要周期是否保證將在預期運行之前分配值。 意思是,摘要循環將有效地像阻塞調用一樣,該阻塞調用保證在允許代碼繼續執行之前,所有的promise均已解決。
function someService(){
var deferred = $q.defer();
deferred.resolve(myObj);
return deferred.promise;
}
it ('testing promise', function() {
var res;
var res2;
someService().then(function(obj){
res = "test";
});
someService().then(function(obj){
res2 = "test2";
});
$rootScope.$apply();
expect(res).toBe('test');
expect(res2).toBe('test2');
});
摘要循環實際上將像阻塞調用一樣工作,以確保在允許繼續執行代碼之前,所有諾言都已得到解決。
是的,盡管更准確地說,它將保證已解決的諾言的成功回調將運行。
雖然Michal的答案指出了正確的想法,但這里的關鍵是在相關范圍上調用了$apply()
。 這是Angular文檔中的示例:
it('should simulate promise', inject(function($q, $rootScope) {
var deferred = $q.defer();
var promise = deferred.promise;
var resolvedValue;
promise.then(function(value) { resolvedValue = value; });
expect(resolvedValue).toBeUndefined();
// Simulate resolving of promise
deferred.resolve(123);
// Note that the 'then' function does not get called synchronously.
// This is because we want the promise API to always be async, whether or not
// it got called synchronously or asynchronously.
expect(resolvedValue).toBeUndefined();
// Propagate promise resolution to 'then' functions using $apply().
$rootScope.$apply();
expect(resolvedValue).toEqual(123);
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.