簡體   English   中英

測試角度服務,異步返回Jasmine 2.0中的$ q Promise

[英]Test Angular Service that Returns a $q Promise in Jasmine 2.0 Asynchronously

我有一個測試承諾結果的規范。

承諾解決,但thencatch ,並finally處理似乎永遠火,並調用done();

因此,規范超時並失敗(請參閱Chrome Developer Console的屏幕截圖)。

Jasmine套件和規格

describe("promise suite", function () {
        var someMethod = function() {
            var deferred = $q.defer();
            setTimeout(function() {
                console.log('All done calling resolve');
                deferred.resolve('all done');
            }, 500);
            return deferred.promise;
        }
        iit("promise spec", function (done) {
            someMethod()
                .then(function(message) {
                    console.log('promise method resolved, running expectation');
                    expect(message).toBe('all done');
                    done();
                })
                .catch(function(error) {
                    console.log('promise was rejected ', error);
                    done();
                })
                .finally(function() {
                    console.log('calling done from finally');
                    done();
                });
        });
    });

在此輸入圖像描述

$ q promises在下一個摘要中得到解決...所以你需要觸發一個摘要:

$rootScope.$digest();

嘗試使用plunkr中的代碼並且它正常工作,請參閱控制台輸出。

由於示例中沒有app引導程序,我使用https://docs.angularjs.org/api/ng/function/angular.injectorng模塊來獲取$q服務

http://plnkr.co/edit/pIZ8LVtlyERXVxQB9HI2?p=preview

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM