2017-07-06 44 views
1

我正在嘗試編寫函數的單元測試,並且出現錯誤。我也不確定如何正確測試函數的其他部分。TypeError:undefined不是單元測試茉莉花時的對象

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(); 
    }); 

}); 

當我運行這個測試我得到這個錯誤:

TypeError: undefined is not an object (evaluating 'response.data.translationMap')

我需要嘲笑response.data .translations或分配json結構? (translation map:{'email':'email','forgotPassword':'Forgot password?'})

另外,我不確定如何正確測試函數的其他部分,如if語句或返回可觀察值。作爲單元測試的新成員,任何建議/幫助都非常感謝。

回答

1

您的方法dictionaryMap接受2個參數 - 第一個是loggedIn(推測是布爾值),第二個是response。在該方法的第一行(在致電configureMomentLocale之前),您有一行const translations = this.convertToArrays(response.data.translations);,該行預計response變量具有名爲data的屬性。

在您的測試,你就行了service.dictionaryMap({}, false); 2個錯誤:

  1. 你設定以相反的順序的論點 - 你應該把布爾參數第一和對象1秒
  2. 對象沒有名爲data

該行應糾正爲類似於service.dictionaryMap(false, { data: {} });。您甚至可能需要爲data對象定義translations屬性 - 它確實取決於this.convertToArrays函數的作用以及它如何處理undefined值。

+1

我覺得很蠢!我不敢相信我把他們弄錯了。非常豐富的答案,我從中學到了。謝謝。 –