2017-08-15 129 views
1

我有以下異步函數:測試錯誤處理茉莉花

async $onInit() { 
    try { 
     this.settings = await this.Service.getSettings(this.companyId); 
    } catch (error) { 
     this.uiFeedback.showSystemError('There was an error processing the request.', error); 
    } 
} 

我想測試,如果功能如果異步函數捕獲錯誤時顯示錯誤。目前唯一的規格併成功設法做到,這是下列:

it('should show error if api call to get availability settings fails',() => { 
    Company.getSettings =() => { 
     throw new Error(); 
    }; 
    try { 
     cmp.$onInit().catch(() => {}); 
    } 
    catch (error) { 
     expect(uiFeedback.showSystemError).toHaveBeenCalled(); 
    } 

}); 

所以基本上我需要我的測試中增加兩個附加的catch塊來得到這個測試工作。否則,我得到以下錯誤:

ERROR: 'Unhandled promise rejection', 'error' 

有沒有更好的方式來做到這一點?

回答

2

所以事實證明,問題是如何karma處理異步函數的錯誤。 $onInit函數中未定義this.uiFeedback。然而,業力沒有顯示uiFeedback是未定義的錯誤,直到我在Chrome中運行測試並在那裏檢查控制檯。當用業力茉莉測試async函數時,每個人都需要注意。