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