I need to create unit test for @HostListener but I have no idea how to write it since it on top of component,
@HostListener('document:click', ['$event']) onDocumentClick(event) {
if (this.activeEvent) {
this.activeEvent = '';
} else {
this.showList = false;
}
this.resetDropdown(event.target.id);
}
What is the best way write unit test for this case?
You could try:
// feel free to change `body` to whatever you wish to send the click to
const body = fixture.nativeElement.querySelector('body');
body.click();
// see if `onDocumentClick` gets called that way
Another option you have, since @HostListener
is already tested by Angular, you can just call onDocumentClick
with your mocked object.
const resetSpy = spyOn(component, 'resetDropdown');
const mockedEvent = { target: { id: 'xyz' } };
component.onDocumentClick(mockedEvent);
expect(resetSpy).toHaveBeenCalledWith('xyz');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.