Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test document clicks in unit tests in angular

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?

like image 390
splintor Avatar asked Apr 17 '18 12:04

splintor


2 Answers

Use document.dispatchEvent:

 it('should handle document click', () => {
    component.dropdownIsOpen = true;
    document.dispatchEvent(new MouseEvent('click'));
    expect(component.dropdownIsOpen).toBe(false);
  });
like image 96
CornelC Avatar answered Nov 15 '22 03:11

CornelC


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.

like image 22
JB Nizet Avatar answered Nov 15 '22 03:11

JB Nizet