title: Angular - Unit testing keypress
body: <p>I have a function that detects a keypress and if the key pressed = escape, a function is fired.</p>
  
  <p>I am having trouble with faking the KeyboardEvent itself to be passed in.</p>
  
  <p>I saw <strong><a href="https://stackoverflow.com/questions/41135875/unable-to-simulate-keypress-event-in-angular-2-unit-test-jasmine">this post</a></strong>, but implementing this solution yields the following output (I console.logged the event itself):</p>
  
  <blockquote>
    <p>LOG: KeyboardEvent{isTrusted: false}
    Chrome 68.0.3440 (Mac OS X 10.13.6) ConfirmationComponent should call onDeny when ESCAPE button pressed FAILED
        Expected spy onDeny to have been called.</p>
  </blockquote>
  
  <p><strong>component.ts</strong></p>
  
  <pre><code>@HostListener('window:keyup', ['$event'])
    keyEvent(event: KeyboardEvent) {
      console.log(event);
      // Press escape - close dialog with simulated 'cancel' click
      if (event.code === 'Escape') {
        this.onDeny();
      }
    }
  
    onDeny() {
       // something is done here
    }
  </code></pre>
  
  <p><strong>test.ts</strong></p>
  
  <pre><code>it('should autofocus on cancel button on init', () =&gt; {
      spyOn(component, 'onDeny');
      component.keyEvent(ESCAPE);
      expect(component.onDeny).toHaveBeenCalled();
    });
  </code></pre>