In Angular I have to test the following code:
@HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
    const targetElement = event.target as HTMLElement;
    if (targetElement.classList.contains('mybtn')) {
     this.prop = 'ok';
    }
}
The following test fails:
    it('Should succeed', () => {
        const spyDocumentClick = spyOn(component, 'onDocumentClick').and.callThrough();
        component.prop = '';
        fixture.detectChanges();
        const btn = debugElement.query(By.css('.mybtn'));
        expect(btn).not.toEqual(null); // ok
        btn.nativeElement.dispatchEvent(new MouseEvent('click'));
        fixture.detectChanges();
        expect(spyDocumentClick).toHaveBeenCalled(); // fail
        expect(component.prop).toBe('ok'); //fail
    });
I also tried to create dummy html element and change target of new MouseEvent
Appreciate for help
Well, it works with the following code:
    it('Should succeed', () => {
        const spyDocumentClick = spyOn(component, 'onDocumentClick').and.callThrough();
        component.prop = '';
        fixture.detectChanges();
        const btn = debugElement.query(By.css('.mybtn'));
        expect(btn).not.toEqual(null); // ok
        const event = new MouseEvent('click',
            {
                view: window,
                bubbles: true,
                cancelable: true,
                relatedTarget: document
            });
        btn.nativeElement.dispatchEvent(event);
        fixture.detectChanges();
        expect(spyDocumentClick).toHaveBeenCalled(); // ok
        expect(component.prop).toBe('ok'); //ok
    });
                        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