title: How to unit test an Hostlistener onChange event in a directive in angular?
body: <p>I created an directive to allow only numbers for a input field and I want to cover this directive with unit test. But I don't know how to cover the <code>@HostListener('input') onChange()</code> part of my code.</p>
  <p>The directive:</p>
  <pre><code>import { Directive, ElementRef, Input, HostListener, Renderer2 } from '@angular/core';
  
  @Directive({
    selector: '[onlyNumbers]'
  })
  
  export class OnlyNumbersDirective {
    @Input() onlyNumbers: boolean | undefined;
    
    constructor(private el: ElementRef, private renderer2: Renderer2) {
    }
    
    @HostListener('input') onChange() {
      if(this.onlyNumbers) {
        const { value } = this.el.nativeElement;
        this.renderer2.setProperty(this.el.nativeElement, 'value', value.replace(/[^0-9]/g, ''));
      }
    }
  }
  </code></pre>
  <p>Unit test which I tried:</p>
  <pre><code>import { TestBed, ComponentFixture } from '@angular/core/testing';
  import { OnlyNumbersDirective } from './onlyNumbers.directive';
  import { Component, Input, OnInit} from '@angular/core';
  
  // Create component to test
  @Component({
    template: `&lt;input type=&quot;text&quot; [ngModel]=&quot;value&quot; [onlyNumbers]=&quot;enableNumbers&quot;/&gt;`
  })
  class TestComponent implements OnInit {
      @Input() enableNumbers = true;
      @Input() value : any;
  
      ngOnInit() {
          this.enableNumbers = true;
          this.value = '123a'
      }
  }
  
  describe('OnlyNumbersDirective', () =&gt; {
    let component: TestComponent;
    let fixture: ComponentFixture&lt;TestComponent&gt;;
  
    beforeEach(() =&gt; {
      TestBed.configureTestingModule({
        declarations: [
          TestComponent,
          OnlyNumbersDirective
        ]
      });
  
      fixture = TestBed.createComponent(TestComponent);
      component = fixture.componentInstance;
    });
  
    it('should create component', () =&gt; {
      expect(component).toBeDefined();
    });
  
    it('should allow numbers only', () =&gt; {
      const debugEl: HTMLElement = fixture.debugElement.nativeElement;
      const input: HTMLElement = debugEl.querySelector('input');
  
      fixture.detectChanges();
  
      expect(input.value).toBe('123');
    });
  });
  </code></pre>
  <p>How can I cover the <code>@HostListener('input') onChange()</code> part with Jasmine/Karma in Angular?</p>