[英]TypeError: undefined is not an object when unit testing with jasmine
我正在嘗試為函數編寫單元測試,但出現錯誤。 我也不確定如何正確測試函數的其他部分。
private dictionaryMap (loggedIn, response) {
const translations = this.convertToArrays(response.data.translations);
this.configureMomentLocale(language);
if (!loggedIn) {
this.cachePublicDictionary(translations);
}
// not testing this part
this.dictionary = new Dictionary({
translationMap: Object.assign({}, this.getPublicDictionaryFromCache() || {}, translations),
});
return this.rx.Observable.of(this.dictionary);
}
到目前為止,我的單元測試如下所示:
describe('dictionaryMap', () => {
it('calls configureMomentLocale()', () => {
const foo = {
'foo':'bar',
};
spyOn(service, 'configureMomentLocale');
service.dictionaryMap({}, false);
expect(service.configureMomentLocale).toHaveBeenCalled();
});
});
當我運行此測試時,出現此錯誤:
類型錯誤:未定義不是對象(評估“response.data.translationMap”)
我是否需要模擬 response.data.translations 或分配 json 結構? (translationMap: {'email': 'email', 'forgotPassword': '忘記密碼?'})
另外,我不確定如何正確測試函數的其他部分,例如 if 語句或返回 observable。 我是單元測試的新手。
您的方法dictionaryMap
接受 2 個參數 - 第一個是loggedIn
(大概是布爾值),第二個是response
。 在該方法的第一行(在調用configureMomentLocale
之前)你有一行const translations = this.convertToArrays(response.data.translations);
它期望response
變量具有名為data
的屬性。
在您的測試中,您在service.dictionaryMap({}, false);
行上有 2 個錯誤service.dictionaryMap({}, false);
:
data
的屬性該行應該更正為類似於service.dictionaryMap(false, { data: {} });
. 您甚至可能需要為data
對象定義translations
屬性 - 這實際上取決於this.convertToArrays
函數的作用以及它如何處理undefined
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.