簡體   English   中英

類型錯誤:使用 jasmine 進行單元測試時未定義不是對象

[英]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);

  1. 您以相反的順序設置參數 - 您應該首先放置布爾參數,然后再放置對象
  2. 該對象沒有名為data的屬性

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM