组件测试中的角度单击选择选项 [英] Angular click select option in component test

查看:74
本文介绍了组件测试中的角度单击选择选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试以下尝试在选择下拉列表中单击一个选项,但这些选项均无效.

I have tried the following to try to click an option in a select dropdown none of which work.

selectEl = fixture.debugElement.query(By.css('#dropdown'));
selectEl.nativeElement.options[3].nativeElement.dispatchEvent(new Event('click'));
selectEl.queryAll(By.css('option'))[3].nativeElement.click();
selectEl.nativeElement.options[3].nativeElement.click();

我每次运行fixture.detectChanges();来运行变化检测,但是当我去检查元素值时它并没有变化. expect(selectEl.nativeElement.options[selectEl.nativeElement.selectedIndex].textContent).toBe('name2');

After each i run fixture.detectChanges(); to run the change detection but when I go to check the elements value it hasn't changed. expect(selectEl.nativeElement.options[selectEl.nativeElement.selectedIndex].textContent).toBe('name2');

我错过了一些简单的方法来使它正常工作吗?

Am I missing something simple to get this to work?

推荐答案

更改下拉列表的所选选项的方法是设置下拉列表的值,然后调度change事件.

The way to change the selected option of a dropdown is to set the dropdown value and then dispatch a change event.

您可以使用以下答案作为参考: 角度单元测试选择onChange间谍对空值

You can use this answer as reference: Angular unit test select onChange spy on empty value

在您的情况下,您应该执行以下操作:

In your case, you should do something like this:

  const select: HTMLSelectElement = fixture.debugElement.query(By.css('#dropdown')).nativeElement;
  select.value = select.options[3].value;  // <-- select a new value
  select.dispatchEvent(new Event('change'));
  fixture.detectChanges();

这篇关于组件测试中的角度单击选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆