How to cover unit test case for addEventListener in Angular 9

Total
1
Shares

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);
  });
}

Solution

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);
}));
Leave a Reply

Your email address will not be published. Required fields are marked *