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); }); } 
1
  • You can try to trigger a keydown keyboard event using dispatchEvent Commented May 23, 2021 at 10:55

1 Answer 1

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); })); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.