简体   繁体   English

如何对垫自动完成选项的选择进行单元测试?

[英]How to unit test selection of a mat-autocomplete option?

How can I programmaticaly trigger the selection of an option of the mat-autocomplete list in a unit test? 如何在单元测试中以编程方式触发对垫自动完成列表选项的选择?

I am trying to write unit tests for a component that includes a mat-autocomplete. 我正在尝试为包含mat-autocomplete的组件编写单元测试。 The component is somewhat complex with the use of ngModel, displayWith, ... so I would like to programmaticaly trigger the selection of an option of the mat-autocomplete list and test the effects this causes. 该组件在使用ngModel,displayWith,...时有些复杂,因此我想以编程方式触发对mat-autocomplete列表的选项的选择,并测试由此引起的效果。

Something like this would be what I am looking for (unfortunately the MatAutocomplete API does not have such a method): 这样的事情会是什么我要找(不幸的是, MatAutocomplete API 没有这样的一种方法):

const autocompleteComponent = fixture.debugElement.query(By.css('mat-autocomplete')).componentInstance as MatAutocomplete;
const selectedOptionIndex = 0;
autocompleteComponent.selectOption(selectedOptionIndex);

How could I achieve something similar? 我怎样才能取得类似的成绩?

Angular Material team already tested @Output() optionSelected event, so in your case, it'll enough to test only handler of this event. Angular Material团队已经测试了@Output() optionSelected事件,因此在您的情况下,仅测试该事件的处理程序就足够了。

But, if you really need to do it, you can achieve that as Angular Material team done it in their unit tests: 但是,如果您确实需要这样做,可以像Angular Material团队在其单元测试中那样实现:

const options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>;
options[1].click();
fixture.detectChanges();

More details here , line 615 , unit test: 'should update control value when option is selected with option value' . 此处的更多详细信息,行615 ,单元测试: 'should update control value when option is selected with option value'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Mat-autocomplete - 如何访问选定的选项? - Mat-autocomplete - How to access selected option? 未选择 mat-autocomplete 选项 - mat-autocomplete option not selected 为使用 mat-autocomplete 的组件编写单元测试 - Writing unit test for component which uses mat-autocomplete 为过滤客户的 mat-autocomplete 编写单元测试 - Writing unit test for mat-autocomplete that filters customers 如何对 Angular 中的 mat-autocomplete 过滤搜索结果的值更改进行单元测试? - How to unit-test a valuechange of mat-autocomplete filtered search result in Angular? 如何检测用户何时清除 mat-autocomplete 的选择? - How to detect when user clears selection of mat-autocomplete? 如何在 setValue 后突出显示 angular mat-autocomplete 中的选项值? - How to highlight option value in angular mat-autocomplete after setValue? Angular mat-autocomplete:如何显示选项名称而不是输入中的值 - Angular mat-autocomplete : How to display the option name and not the value in the input Angular 6:如何访问 mat-autocomplete 下拉列表中的所有选项值? - Angular 6: how to access ALL option values in mat-autocomplete dropdown? 如何检测在 Angular 中选择了 mat-autocomplete 选项? - How to detect mat-autocomplete option is selected in Angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM