0

How to cover the addEventListener internal code.

any-angular.component.ts

openModalWithKeypress() {
  const div = this.elm.nativeElement.querySelector('div');
  div.addEventListener('keydown', e => {
    this.openModal(e);
  });
}
R. Richards
  • 24,603
  • 10
  • 64
  • 64
Sudhakar Lahane
  • 137
  • 1
  • 2
  • 12
  • You can try to trigger a [keydown keyboard event](https://stackoverflow.com/questions/3368578/trigger-a-keypress-keydown-keyup-event-in-js-jquery) using dispatchEvent – HDJEMAI May 23 '21 at 10:55

1 Answers1

1

You can execute your unit test in the fakeAsync zone. Then, you need to invoke tick() just after dispatching the keydown event. This could look as follows:

it('#keydown should open modal', fakeAsync(() => {

  // given
  spyOn(anyComponent, 'openModal') 
  const divElement = <HTMLDivElement> fixture.debugElement.nativeElement.querySelector('div');
  const event = new KeyboardEvent('keydown', { key: 'x' });

  // when
  divElement.dispatchEvent(event);
  tick();

  // then
  expect(anyComponent.openModal).toHaveBeenCalledWith(event);
}));
uminder
  • 23,831
  • 5
  • 37
  • 72