尝试使用正确的值正确选择菜单更改事件。它似乎在解雇,但价值并没有改变。
我的组件中有这个选择菜单:
<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方法中改变。我知道该方法正在触发,因为当我测试expect(component.test).toEqual('blah')时它会通过:
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 :(得分:5)
在测试中选择select元素之前,你应该运行
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(...)一起)。
我希望这有助于某人。