title: Angular How to test @HostListener
body: <p>I have the following directive. When applied to an input element, it checks for characters and calls preventDefault when the character is forbidden:</p>
  
  <pre><code>@Directive({
   selector: '[cdtPreventInput]'
  })
    export class PreventInputDirective implements OnInit {
  
    // the list of characters that are to be prevented
    @Input() cdtPreventInput: String;
  
    constructor() { }
  
    ngOnInit() {
      if (!this.cdtPreventInput) {
        throw new Error('cdtPreventInput cannot be used without providing a 
            list of characters.');
      }
    }
  
   @HostListener('keypress', ['$event']) onKeyPress(event) {
     if (_.includes(this.cdtPreventInput.split(','), event.key)) {
      event.preventDefault();
    }
  }
  </code></pre>
  
  <p>Works fine, but I can't figure out how to test it. I have the following so far: </p>
  
  <pre><code>describe('PreventInputDirective', () =&gt; {
    let fixture;
    let input: DebugElement;
  
    beforeEach(() =&gt; {
      fixture = TestBed.configureTestingModule({
        declarations: [PreventInputDirective, TestComponent]
      }).createComponent(TestComponent);
  
      input = fixture.debugElement.query(By.directive(PreventInputDirective));
    });
  
    it('should create an instance', () =&gt; {
      const directive = new PreventInputDirective();
      expect(directive).toBeTruthy();
    });
  
   it('should prevent default keypress event', () =&gt; {
      const event = new KeyboardEvent('keypress', {
        'key': '.'
      });
       input.nativeElement.dispatchEvent(event);
  
       expect(input.nativeElement.value).toEqual('');
    });
  
    @Component({
      template: `&lt;input cdtPreventInput="." /&gt;`
    })
    class TestComponent { }
  });
  </code></pre>
  
  <p>It's not working though. The keypress event is not triggered. Any idea how to test this directive ? </p>