How do I test events in Angular Material Autoplete? I'm trying to test this code and would like to know how to pass in the event
argument to the method:
onOptionSelect(event: MatAutopleteSelectedEvent) {
this.selectedOption = event.option.value;
}
Edit: To clarify, I'd like to know how to mock an event of type MatAutopleteSelectedEvent
so that I can pass it to my method in test.
How do I test events in Angular Material Autoplete? I'm trying to test this code and would like to know how to pass in the event
argument to the method:
onOptionSelect(event: MatAutopleteSelectedEvent) {
this.selectedOption = event.option.value;
}
Edit: To clarify, I'd like to know how to mock an event of type MatAutopleteSelectedEvent
so that I can pass it to my method in test.
2 Answers
Reset to default 5Instead 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 piler to treat this object as MatAutopleteSelectedEvent .
// given
const newValue = 'something';
const event: MatAutopleteSelectedEvent = {
option: {
value: newValue
}
} as MatAutopleteSelectedEvent;
// when
ponent.onSelect(event);
// then
expect(ponent.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 acplish anything more than one of the above approaches other than making sure that MatAutoplete makes selections properly, and you shouldn't have to test that IMO.