2016-09-26 3 views
3

양방향 바인딩이 작동하는지 테스트하기 위해 구성 요소에 대한 테스트를 작성하려고합니다.각도 2 양방향 바인딩 입력 값을 테스트하는 방법

한쪽에 나는 그렇게 보이는 검사를 (그리고 그것은 통과) :

it('should bind displayed value to the SearchComponent property',() => { 
    searchComponent.searchBoxValue = 'abc'; 
    searchCompFixture.detectChanges(); 
    expect(inputEl.nativeElement.getAttribute('ng-reflect-model')).toBe('abc'); 
}); 

반면에

searchCompFixture = TestBed.createComponent(SearchComponent); 
inputEl = searchCompFixture.debugElement.query(By.css('#search-box-input')); 

<input 
    id="search-box-input" 
    [(ngModel)]="searchBoxValue"\> 

내가 어디를 원한다 먼저 입력 요소의 값을 설정하는 테스트를 작성하고 SearchComponent 특성 값이 변경되었는지 점검하십시오. 내 시도 : searchComponent.searchBoxValue 값이 설정되지 않기 때문에

it('should bind SearchComponent property to the displayed value', fakeAsync(() => { 
    inputEl.nativeElement.value = 'abc'; 
    let evt = new Event('input'); 
    inputEl.nativeElement.dispatchEvent(evt); 

    tick(); 

    searchCompFixture.detectChanges(); 
    expect(searchComponent.searchBoxValue).toBe('abc'); 
})); 

하지만이 작동하지 않습니다. 어떤 아이디어가 이것을 고치는 방법?

답변

3

입력 필드 (idk why)의 값을 업데이트하기 전에 detechtChanges이 필요합니다.

it('should bind SearchComponent property to the displayed value', fakeAsync(() => { 
    searchCompFixture.detectChanges(); 

    inputEl.nativeElement.value = 'abc'; 
    let event = new Event('input'); 
    inputEl.nativeElement.dispatchEvent(event); 

    tick(); 
    expect(searchCompFixture.componentInstance.searchBoxValue).toEqual('abc'); 
})); 

편집 : 다음은 작업 테스트입니다 내가 테스트 should bind displayed value to the SearchComponent property 또 다른 개선을 발견했다. 내가 그것에 대해 싫어했던 것은 이상한 각도 속성 ng-reflect-model을 사용했는데 일반적인 방법이 아니라는 것입니다. inputEl.nativeElement.value. 이 문제는 value이 각도로 아직 설정되지 않았다는 것입니다.

다음과 같이 테스트를 변경하면 문제가 해결되고 더 이상 마법이 필요하지 않습니다. hoorah!

it('should bind displayed value to the SearchComponent property', fakeAsync(() => { 
    searchComponent.searchBoxValue = 'abc'; 

    searchCompFixture.detectChanges(); 
    tick(); 
    searchCompFixture.detectChanges(); 


    expect(inputEl.nativeElement.value).toBe('abc'); 
}));