Jor*_*ald 0 jasmine karma-jasmine angular
试图让我的选择菜单更改事件以正确的值正确触发。它似乎正在触发,但价值没有改变。
我的组件中有以下选择菜单:
<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>
Run Code Online (Sandbox Code Playgroud)
我有这个变化事件:
public changeSeason(seasonId: number) {
this.test = 'blah'; //for testing sake
console.log('change season ' + seasonId)
this.seasonId = seasonId;
this.notify.emit(this.seasonId);
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试像下面的代码一样对其进行测试,但是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
}));
Run Code Online (Sandbox Code Playgroud)
小智 5
在测试中获取选择元素之前,应运行
fixture.detectChanges();
Run Code Online (Sandbox Code Playgroud)
将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');
});
Run Code Online (Sandbox Code Playgroud)
请注意,我使用HTMLSelectElement的selectedIndex属性选择第二个选项来模拟更改的选择(以及distachEvent(...))。
我希望这可以帮助别人。
| 归档时间: |
|
| 查看次数: |
1266 次 |
| 最近记录: |