2016-10-12 46 views
2

我一直使用下面的代碼來測試下面的代碼示例。

function loadAccounts() { 
    return AccountCaller.loadAccounts() 
    .then(function(response){ 
    AccountsModel.accounts = response.accounts; 
    }) 
    .catch(function(error){ 
    ErrorHandler.raise(error); 
    }); 
} 

var spy= spyOn(mock, 'loadAccounts').andCallFake(function() { 
     return { 
      then: function (callback) { 
       return callback(response); 
      } 
     }; 
    }); 

上面的代碼工作正常的「然後」,但我最近推出了「.catch」現在我的測試中失敗‘類型錯誤:無法讀取屬性‘’未定義的’陷阱。

關於如何處理'.catch'元素的任何想法,如果我刪除它然後代碼測試運行良好!

乾杯

回答

2

在你的then間諜你有return callback(response);,但回調不返回任何東西,這就是爲什麼你在你的錯誤提示undefined。你要返回的東西至少需要附加一個catch方法。您可以測試像這樣的東西:

var spy= spyOn(mock, 'loadAccounts').andCallFake(function() { 
    return { 
     then: function (callback) { 
      callback(response); 
      return {catch: function() {}}; 
     } 
    }; 
}); 

^^這不一定是如何我做到這一點,但它應該讓你在正確的方向前進。考慮返回包含在Promise中的callback(response)的結果。

+0

謝謝我現在得到'TypeError:AccountCaller.loadAccounts(...)。then(...)。然後不是一個函數'。反應的方式設置爲response = {};與一些模擬帳戶數據 –

+0

所有工作現在忽略批准需要重新啓動;) –