2015-11-01 24 views
2

以下是我的函數的外觀。如何使用承諾測試角度工廠函數在茉莉花中引發錯誤

var myFunc = function(){ 
    return functionReturningaPromise() 
      .then(function(){ 
       //success, doesn't matter what happens here 
      }) 
      .catch(function(err){ 
       //handle error here and then throw to handle higher 
       throw new Error('Error in my function'); 
      }) 
} 

我需要這個函數來處理這個函數內部的錯誤,然後拋出一個錯誤來處理更高的級別。但我不知道如何用茉莉花來測試它。我知道如何控制的承諾,用於測試和我的基本設置是這樣的:

it('Should throw an error', inject(function(alert) { 
    var instance = instanceFactory.createInstance(someData); 
    var deferred = $q.defer(); 
    spyOn(someFactory, 'someMethod').and.returnValue(deferred.promise); 

    //instance contains the throwing function above 

    instance.myFunc(otherData); 

    deferred.reject({data: '12 - error'}); 
    $rootScope.$digest(); 

    expect(instance.myFunc).toThrow(); 

})); 

顯然,錯誤不是由茉莉發現。因此,如何測試錯誤扔在這種情況下

回答

2

$q不與本地throw很好地工作,你應該使用$q API重新擲或創建承諾鏈中新的錯誤。一些Q/A,以瞭解它:

該解決方案將使用return $q.reject('Error in my function')而不是throw new Error('Error in my function');

但開放的問題是如何測試它。基本上,你可以使用承諾鏈,並添加更多的.catch()測試來檢查錯誤,並測試使用Jasmine Async API

it('should throw an error', function (done) { 
// ----- use Jasmine async API -------^^^ 

    var instance = instanceFactory.createInstance(someData); 
    var deferred = $q.defer(); 
    spyOn(someFactory, 'someMethod').and.returnValue(deferred.promise); 

    // here we continue catching and check the error 
    var promise = instance.myFunc(otherData); 
    promise.catch(function (err) { 
     expect(err).toBe('Error in my function'); 
     done(); 
    }); 

    deferred.reject({data: '12 - error'}); 
    $rootScope.$digest(); 
}); 

Here is a working sample(開放script.js文件中的邊欄)

+0

#Michael Radionov我有一個類似的問題和你的解決方案的工作,但我擔心假陽性: 函數A(){0} {0} {0} } //一切正常 $ q.resolve(); 函數B(){拋出({myError:{錯誤:ERROR_MESSAGE')}}}' 陌生人的是我已經通過應用解決方案的,是得到了以下錯誤: '{預期myError: {error:'error_message'}} {myError:{error:'error_message'}}' 但是最終,當我在'promise前面移動'$ rootScope。$ digest'行**時, catch etc'部分 – Gargaroz

+1

關於錯誤消息 - 'toBe'匹配器通過引用比較對象,應該使用'toEqual'來執行深度相等比較。這是因爲你在我的例子中使用錯誤作爲對象與錯誤作爲字符串。雖然我不確定摘要,但如果您在[plunker](http://plnkr.co/)中分享了更新後的代碼,那將會很棒。 –

+0

對不起以前的評論,並提前感謝您的幫助,[這裏是plunkr](http://plnkr.co/edit/2z4LmCSpCL8eTYvPErKH) – Gargaroz