最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular material autocomplete: testing events - Stack Overflow

programmeradmin2浏览0评论

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.

Share edited Aug 23, 2018 at 19:27 Devin asked Aug 22, 2018 at 18:22 DevinDevin 2,0021 gold badge21 silver badges27 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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 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.

发布评论

评论列表(0)

  1. 暂无评论