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();
}));
顯然,錯誤不是由茉莉發現。因此,如何測試錯誤扔在這種情況下
#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
關於錯誤消息 - 'toBe'匹配器通過引用比較對象,應該使用'toEqual'來執行深度相等比較。這是因爲你在我的例子中使用錯誤作爲對象與錯誤作爲字符串。雖然我不確定摘要,但如果您在[plunker](http://plnkr.co/)中分享了更新後的代碼,那將會很棒。 –
對不起以前的評論,並提前感謝您的幫助,[這裏是plunkr](http://plnkr.co/edit/2z4LmCSpCL8eTYvPErKH) – Gargaroz