2017-09-23 65 views
0

試圖讓我的選擇菜單更改事件以正確的值正確觸發。它似乎在開火,但價值沒有改變。單元測試選擇菜單更改事件(未獲取更新值)

我有我的組件此選擇菜單:

<select id="seasonDropDown" style="width:200px;height: 36px;" aria-label="Select a Season" (change)="changeSeason($event.target.value)"> 
     <option *ngFor="let item of seasons" [value]="item.id" [selected]="item.id === seasonId">Season {{item.id}}</option> 
    </select> 

我有這樣的改變事件:

public changeSeason(seasonId: number) { 
    this.test = 'blah'; //for testing sake 
    console.log('change season ' + seasonId) 
    this.seasonId = seasonId; 
    this.notify.emit(this.seasonId); 
    } 

我試圖測試它像下面的代碼,但commponent.seasonId從不改變其默認值。它應該在changeSeason方法中更改。我知道的方法燒製,因爲當我測試期待(component.test).toEqual(「胡說」),它會通過:

it('should emit new season on change event', fakeAsync(() => { 

     let select = fixture.debugElement.query(By.css('#seasonDropDown')).nativeElement; 

     select.value = 2; 
     select.selectedValue = 2; 

     fixture.detectChanges(); 

     select.dispatchEvent(new Event('change')); 
     tick(); 

     fixture.detectChanges(); 


     expect(component.seasonId).toEqual(2); 
     //expect(component.test).toEqual('blah'); this will pass so I know the 
     //changeSeason event is actually getting called 
    })); 

回答

0

之前在測試搶奪選擇元素應該運行

fixture.detectChanges(); 

已將HTML元素正確鏈接到組件及其事件處理程序。 看看我的複製stackblitz。這裏只是測試:

it('should emit new season on change event',() => { 
    fixture.detectChanges(); 
    let select = fixture.debugElement.query(By.css('#seasonDropDown')).nativeElement as HTMLSelectElement; 

    select.selectedIndex = 1; // {id:2} 
    select.dispatchEvent(new Event('change')); 
    fixture.detectChanges(); 

    expect(+component.seasonId).toEqual(2); 
    expect(component.test).toBe('blah'); 
}); 

請注意,我用HTMLSelectElement的selectedIndex屬性來選擇第二個選項(與distachEvent(...)在一起)來模擬一個改變的選擇。

我希望這可以幫助別人。