如何在 Angular 9 中覆盖 addEventListener 的单元测试用例

How to cover unit test case for addEventListener in Angular 9

如何覆盖addEventListener内部代码。

任何-angular.component.ts

openModalWithKeypress() {
  const div = this.elm.nativeElement.querySelector('div');
  div.addEventListener('keydown', e => {
    this.openModal(e);
  });
}

您可以在发送 keydown event 后立即在 fakeAsync zone. Then, you need to invoke tick() 中执行您的单元测试。这可能如下所示:

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