[英]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.