How do I test events in 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:
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.
Simple autocompleteStart by creating the autocomplete panel and the options displayed inside it. Each option should be defined by a mat-option tag. Set each option's value property to whatever you'd like the value of the text input to be when that option is selected.
The <mat-autocomplete>, an Angular Directive, is used as a special input control with an inbuilt dropdown to show all possible matches to a custom query. This control acts as a real-time suggestion box as soon as the user types in the input area.
Answers 1 : of How to clear mat- autocomplete when no option is selected from autocomplete dropdown. You can remove the formControl-binding from your input and when you select an option you set that id to your form.
Here is the place we have to use the [DisplayWith]. This will pass the selected value to the function and show the value in the input that returning from the function. This is my DisplayWith function that will accept the value and get the object from the filteredOptions array and return the CustomerId.
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 .
// 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
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With