簡體   English   中英

HostListener 的 Angular 單元測試(調整窗口大小)

[英]Angular Unit Testing for HostListener (Window Resize)

我有一個包含以下代碼的組件文件

@HostListener('window:resize', ['$event'])
onResize(event) {
    this.width = event.target.innerWidth;
}

我想測試一下。 我在我的規范文件中嘗試了以下代碼。

window.dispatchEvent(new Event("resize");
expect(component.onResize).toHaveBeenCalled();

但它不起作用。 任何幫助將不勝感激。

我遇到了同樣的問題,我在由 resize 事件觸發的函數上使用 Spy 解決了這個問題。

 it('should trigger onResize method when window is resized', () => {
    const spyOnResize = spyOn(component, 'onResize');
    window.dispatchEvent(new Event('resize'));
    expect(spyOnResize).toHaveBeenCalled();
 });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM