We have a drop-down component that has its dropdown collapsed on any outside click. This is implemented as:
@HostListener('document:click', ['$event'])
public documentClick(event) {
if (this.dropdownIsOpen && !event.clickedFromMe) {
this.dropdownIsOpen = false;
}
}
How can this code be tested? When using TestBed.createComponent
, only the component seems to be created, and it is not inside any document, so how can I simulate a click outside of that component?
Use document.dispatchEvent
:
it('should handle document click', () => {
component.dropdownIsOpen = true;
document.dispatchEvent(new MouseEvent('click'));
expect(component.dropdownIsOpen).toBe(false);
});
It is inside a document.
Just use
const compiled: HTMLElement = fixture.nativeElement;
compiled.ownerDocument.dispatchEvent(new Event('click'));
An alternative if to create a fixture for a test component which uses your component in its template, and also some sibling button, for example, and to click on this sibling button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With