模拟<select>元素中的选择

时间:2017-06-27 13:39:42

标签: angular karma-runner

在一个角度反应形式我使用一个简单的选择元素: &lt; select class =“form-control”formControlName =“item”id =“item”[value] =“form.get('item')。value”&gt;   &lt; option * ngFor =“let item of items”[value] =“item.key”&gt; {{item.value}}&lt; / option&gt; &LT; /选择&GT; 我想模拟在单元测试中选择的元素: (fixture.debugElement.query(By.css('option [value =“item2”]'))。nativeElement as HTMLElement).click(); 选择有效,它是好的元素(我可以更改它的属性),但点击不起作用。我试着预先选择元素: (fixture.debugElement.query(By.css('select'))。nativeElement as HTMLElement).click(); 但仍然没有。我还尝试直接在DebugElement而不是nativeElement上调用triggerEventHandler,并将“item2”作为参数。 所以我有点不可选择。 谢谢

1 个答案:

答案 0 :(得分:2)

试试这个

let hl:HTMLSelectElement = (fixture.debugElement.query(By.css('select')).nativeElement as HTMLSelectElement);
hl.value='newvalue'; //set the new value
hl.dispatchEvent(new Event('change')); //this is what triggers angular to do its magic 
fixture.detectChanges(); 
tick(); //assuming you are doing this inside a fakeAsync

c