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

私は==と(アレイを含む)のオブジェクトを比較すると、JavaScriptで[] == []

を仮定のミスを犯した、または===それらが同じオブジェクトであることを確認します。この場合、それらは同じオブジェクトではありません。

Why isn't [1,2,3] equal to itself in Javascript?

0

matchesが定義されていないかnullの場合、配列型ではありません。 だから、多分比較:

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

試してください:あなたはthis.matchesを宣言した位置に

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

ルック。 など。

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

または:コンストラクタで

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

私は騒いで、[] == []とは思わない –

関連する問題