2017-09-15 3 views
1

3 개의 입력 텍스트가있는 양식이 포함 된 구성 요소가 있습니다. 두 개의 입력은 순수 텍스트 상자이고 ngbTypeahead는 ng-bootstrap의 텍스트 상자입니다. 내 양식은 FormBuilder (반응 형 양식)를 사용하여 작성됩니다. 그래서 this.form.department.value 문자열하지만이 같은 객체가 아닌유닛 테스트 ngbTypeahead가 포함 된 구성 요소

<input type="text" class="form-control" formControlName="name"/> 
... 
<input type="text" class="form-control" formControlName="location"/> 
... 
<input 
    type="text" 
    class="form-control" 
    formControlName="department" 
    [ngbTypeahead]="autocompleteDepartments" 
    [resultFormatter]="formatDepartment" 
    [inputFormatter]="formatDepartment"/> 

구성 요소가 ngbTypeahead

autocompleteDepartments(text$: Observable<string>): Observable<Department> { 
    .... 
} 
formatDepartment(department: Department) { 
    return department.name; 
} 

을위한 기능이 포함되어

this.form = fb.group({ 
    department: [''], 
    name: ['', Validators.required], 
    location: ['', Validators.required] 
}); 

내 템플릿처럼 보인다 :

interface Department { 
    id: number; 
    name: string; 
    foo: boolean; 
    bar: number; 
    ... 
} 

괜찮습니다.

이제 단위 구성 요소 테스트를 위해 세 입력의 값을 설정해야합니다. 두 개의 순수 입력의 , 아무 문제 없습니다 :

const nameHtmlEl = <HTMLInputElement>fixture.debugElement.query(By.css('[formControlName="name"]')).nativeElement; 
nameHtmlEl.value = "Toto"; 
nameHtmlEl.dispatchEvent(new Event('input')); 

그러나 ngbTypeahead 지시문을 입력, 나는 (학과 객체가 아닌 문자열이 될 수있는 그 필요성을) 값을 설정하는 방법을 모른다 : 나는 것을 시도했지만 작동하지 않습니다 :

const departmentHtmlEl = /*<HTMLInputElement>*/ fixture.debugElement.query(By.css('[formControlName="department"]')).nativeElement; 
departmentHtmlEl.value = <Department>{id: 10, name: "Foo", ...}; 
departmentHtmlEl.dispatchEvent(new Event('input')); 

답변

0

난 당신이 선행 입력에 대한 필터링 된 항목 중 하나의 선택을 시뮬레이션하기 위해 노력하고있다 생각합니다.

departmentHtmlEl.value = 'Foo'; 

당신이 이름을 검색 가정 : 나는 이것에 대해 갈 것

방법은 여전히 ​​키 당신이 검색 문자열을 설정하는 것입니다.

그러면 선택을 시뮬레이션합니다. 이것은 당신이

getWindowLinks(fixture.debugElement)[0].triggerEventHandler('click', {}); 

getWindowLinks으로 할 수있는 것은 : 또한

function getWindowLinks(element: DebugElement): DebugElement[] { 
    return Array.from(element.queryAll(By.css('button.dropdown-item'))); 
} 

,이 작품을 만들기 위해 fakeAsync을 사용해야합니다. 샘플 테스트는 다음과 같습니다.

it('sample test', fakeAsync(() => { 
    const departmentHtmlEl = /*<HTMLInputElement>*/ fixture.debugElement.query(By.css('[formControlName="department"]')).nativeElement; 
    departmentHtmlEl.value = 'Foo'; 
    fixture.detectChanges(); 

    tick(300); 
    // this should be more than the number on debounceTime you are using for the search 

    getWindowLinks(fixture.debugElement)[0].triggerEventHandler('click', {}); 
    fixture.detectChanges(); 

    tick(300); 

    // your expectation code here. 
    })); 

희망이 있습니다.