简体   繁体   English

角材料自动完成:测试事件

[英]Angular material autocomplete: testing events

How do I test events in Angular Material Autocomplete?如何在 Angular Material Autocomplete 中测试事件? I'm trying to test this code and would like to know how to pass in the event argument to the method:我正在尝试测试此代码,并想知道如何将event参数传递给该方法:

onOptionSelect(event: MatAutocompleteSelectedEvent) {
  this.selectedOption = event.option.value;
}

Edit : To clarify, I'd like to know how to mock an event of type MatAutocompleteSelectedEvent so that I can pass it to my method in test.编辑:为了澄清,我想知道如何模拟MatAutocompleteSelectedEvent类型的事件,以便我可以在测试MatAutocompleteSelectedEvent其传递给我的方法。

Instead of creating a whole Event object, you can create only a plain object with values required only by the test and use the as keyword to inform the compiler to treat this object as MatAutocompleteSelectedEvent .除了创建整个 Event 对象之外,您还可以只创建一个具有仅测试所需值的普通对象,并使用as关键字通知编译器将此对象视为 MatAutocompleteSelectedEvent 。

// given
const newValue = 'something';
const event: MatAutocompleteSelectedEvent = {
  option: {
    value: newValue
  }
} as MatAutocompleteSelectedEvent;
// when
component.onSelect(event);
// then
expect(component.selectedOption).toEqual(newValue);

There are a couple of options.有几个选项。 You can either call the method directly from your test, or trigger the method using DebugElement.triggerEventHandler .您可以直接从测试中调用该方法,也可以使用DebugElement.triggerEventHandler触发该方法。 In both cases you need to create the event object yourself or mock it and test for the expected results.在这两种情况下,您都需要自己创建事件对象或模拟它并测试预期的结果。

If you want to actually force a manual selection, for example open the list and generate a click event on one of the options, I don't think this is possible (I have tried and searched to no avail - if someone knows how, please post the answer).如果您想实际强制手动选择,例如打开列表并在其中一个选项上生成点击事件,我认为这是不可能的(我已经尝试并搜索无济于事 - 如果有人知道如何,请发布答案)。 Arguably, this isn't necessary because it doesn't accomplish anything more than one of the above approaches other than making sure that MatAutocomplete makes selections properly, and you shouldn't have to test that IMO.可以说,这不是必需的,因为除了确保 MatAutocomplete 正确进行选择之外,它只能完成上述方法之一,并且您不必测试该 IMO。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM