2

我正在嘗試編寫一個測試以確保我的方法根據某個組件的屬性返回正確的值。 因此,在我的單元測試中,我想設置組件屬性的值,然後調用組件的方法,該方法假定基於該值返回一個布爾值,但它不能按預期工作。無法從單元測試中更改組件的屬性

該組件的方法很簡單:

isLoading(): boolean { 
    return this.matches === []; 
} 

,這裏是我目前的單元測試:

it('should have isLoading reflect whether there are matches',() => { 
    expect(component.matches).toBeDefined(); 

    component.matches = []; 
    console.log(component.isLoading()); 
    expect(component.isLoading()).toEqual(true); 

    component.matches = [{name: 'object'}]; 
    console.log(component.isLoading()); 
    expect(component.isLoading()).toEqual(false); 
}); 

兩個console.logs輸出錯誤,我不知道爲什麼。

+0

一個plunkr總是幫助:) – Guntram

+0

請考慮改寫爲後人這一問題。這些不屬於屬性。那麼它聽起來可能很迂腐,實際上這種區別在角模板語言的背景下非常重要。 –

回答

0

如果matches未定義或爲null,則它不是數組類型。 所以你也許比較:

if (this.matches is an array and empty)... 
// but if it is not initialized (undefined) or initialized as null... 

嘗試:

isLoading(): boolean { 
    return !this.matches || (this.matches && this.matches === []); 
    // i would leave the() brackets to make it easier to read 
} 

或例如爲:

isLoading(): boolean { 
    return !this.matches || !this.matches.length; 
} 

看看那裏聲明this.matches的位置。 例如在構造:

constructor(
    public matches: any[] = null 
) {} 

或:

export class MyComponent { 
    public matches: any[] // <- undefined, not initialized 
+1

我悶悶不樂,並假設[] == []它沒有 –