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 same. I noticed a difference between triggerEventHandler() and dispatchEvent(), while dispatchEvent() was triggering the event correctly and directive was triggered, in the case of triggerEventHandler() event wasn't triggered. Can anyone let me know, what's the difference between them, apart from that dispatchEvent() is called on nativeElement.
// directive
export class AlphaNumericCheckDirective {
constructor(private ctrl: NgControl) {
}
@HostListener('input')
onInputChange() {
const pattern = /[^0-9]/g;
const elVal = (this.ctrl.control as AbstractControl).value;
if (pattern.test(elVal)) {
const newVal = elVal.replace(pattern, '');
(this.ctrl.control as AbstractControl).setValue(newVal);
}
}
}
// relevant code of test
it('should allow only numerics', () => {
const fixture = TestBed.createComponent(TestComponent);
const inputEl = fixture.debugElement.query(By.css('input'));
(fixture.componentInstance.testGroup.get('testControl') as
AbstractControl).patchValue('12a');
inputEl.triggerEventHandler('input', null); // not triggering the directive
inputEl.nativeElement.dispatchEvent(new Event('input')); // triggering the directive
});