角度测试HostListener

时间:2019-03-07 21:57:10

标签: angular jasmine

在Angular中,我必须测试以下代码:

@HostListener('document:click', ['$event'])
public onDocumentClick(event: MouseEvent): void {
    const targetElement = event.target as HTMLElement;
    if (targetElement.classList.contains('mybtn')) {
     this.prop = 'ok';
    }
}

以下测试失败:

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

我还尝试创建虚拟html元素并更改新MouseEvent的目标

感谢帮助

1 个答案:

答案 0 :(得分:0)

好吧,它可以使用以下代码:

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