2017-09-23 63 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(...)在一起)来模拟一个改变的选择。

我希望这可以帮助别人。