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

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

问题描述

我尝试了以下方法来尝试单击选择下拉列表中的一个选项,但都不起作用.

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.

您可以使用此答案作为参考:Angular 单元测试选择 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天全站免登陆