简体   繁体   中英

Angular test HostListener

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM