Angular - Unit testing keypress

physicsboy

I have a function that detects a keypress and if the key pressed = escape, a function is fired.

I am having trouble with faking the KeyboardEvent itself to be passed in.

I saw this post, but implementing this solution yields the following output (I console.logged the event itself):

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.

component.ts

@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
  }

test.ts

it('should autofocus on cancel button on init', () => {
    spyOn(component, 'onDeny');
    component.keyEvent(ESCAPE);
    expect(component.onDeny).toHaveBeenCalled();
  });
user4676340

Don't bother implementing a keyboard event: it changes on every browser and usually doesn't even work.

Instead, test your function itself (leave Angular testing behavior to Angular itself):

it('should log event and call self.onDeny() when keyEvent', () => {
  const spy1 = spyOn(component, 'onDeny');
  const spy2 = spyOn(console, 'log');
  const eventMock = {code: 'Escape'};
  component.keyEvent(eventMock);
  expect(spy1).toHaveBeenCalledWith();
  expect(spy2).toHaveBeenCalledWith(eventMock);
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related