What is the difference between dispatchEvent() and triggerEventHandler() in angular unit testing using karma?

后端 未结 2 1111
耶瑟儿~
耶瑟儿~ 2021-01-13 00:13

I am writing unit test for a directive(called on input event), which is modifying an input value on a formControl. I\'ve created a test component in my spec file for the sam

相关标签:
2条回答
  • 2021-01-13 00:35

    triggerEventHandler belongs to Angular. The triggerEventHandler will invoke the event handler only if it was declared on the native element by using Angular event bindings, the @HostListener() or @Output decorators.

    dispatchEvvent comes in handy when we define events via JS native APIs, for eg. RxJS fromEvent observable, etc.

    We can even use dispatchEvent to simulate Angular Material component's event while testing, as triggerEventHandler would not work there since Angular doesn’t know about those events.

    Here's a very interesting article that will help you understand the difference neatly https://netbasal.com/simulating-events-in-angular-unit-tests-5482618cd6c6

    0 讨论(0)
  • 2021-01-13 00:58

    I noticed same issue as well. What I found is triggerEventHandler() works in the button testing scenario but not the input case while dispatchevent works in the input scenario which is your case.

    0 讨论(0)
提交回复
热议问题