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

는 후손이 질문의 문구를 수정 고려하시기 바랍니다. 속성이 속성이 아닙니다. 글쎄 그것은 pedantic으로 들릴지도 모릅니다. 실제로 구별되는 것은 templating 언어의 맥락에서 매우 중요합니다. –

답변

0

I는 가정의 실수 [] == [] 자바 스크립트

==와 (배열을 포함하는) 물체들을 비교하거나 === 그들이 동일한 객체이고이 경우에는 그렇지 않다는 것을 확인합니다.

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... 

시도 :

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

또는 예컨대 : 당신이 this.matches를 선언 위치에

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

봐. 예.

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

또는 : 생성자

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

나는 그것을 채우지 않았고 [] == []라고 생각했다. –

관련 문제