在 Angular 2 中测试由“(window:resize)”事件触发的函数

Posted

技术标签:

【中文标题】在 Angular 2 中测试由“(window:resize)”事件触发的函数【英文标题】:Testing the function triggered by the "(window:resize)" event in Angular 2 【发布时间】:2017-03-29 18:44:52 【问题描述】:

我正在尝试测试由窗口调整大小事件触发的函数(使用 Karma)。在现实世界中一切正常,但是当我尝试在测试中手动触发事件时,该函数永远不会被调用。这会导致测试失败。

这是我的 html

<div id="topnav" 
     class="navbar navbar-graylight header-width" 
     role="banner" 
     (window:resize)="onResize($event)"></div>

这是我的 onResize() 函数:

@Component(
  selector: "main-header",
  templateUrl: "main-header.component.html",
)
export class MainHeaderComponent 

  public itWasTriggered = false;

  public onResize(event) 
    this.itWasTriggered = true;
  

这是我的测试:

it("Why is onResize() not being ran", () =>  
   const heroEl = fixture.debugElement.query(By.css(".navbar-graylight"));
   heroEl.triggerEventHandler("window:resize", null); 
   expect(comp.itWasTriggered).toBe(true);
);

这是检查器中显示的内容:

<div _ngcontent-a-1="" class="navbar navbar-graylight header-width" id="topnav" role="banner">
  <!--template bindings=-->
  <!--template bindings=-->
</div>

【问题讨论】:

您能否确认 div “topnav” 在正文中是否可见?您的灯具是否已将其添加到您的页面上? @WinterSoldier:谢谢,我现在已经添加了上面检查器中显示的内容。 现在你可以尝试用 window.dispatchEvent(new Event('resize')); 替换 heroEl.triggerEventhandler() 吗?如上所述here 我的 resize 事件处理设置有所不同(Observable.fromEvent(window, 'resize')...),但有相同的测试问题。我可以确认@WinterSoldier 对 window.dispatchEvent(new Event('resize')); 的建议确实为我解决了测试问题。谢谢!! 给定一个特定的高度或宽度,测试一下怎么样? window.resizeTo 似乎没有调用处理程序,您不能在只读的 currentTarget 上设置 innerWidth 【参考方案1】:

我遇到了同样的问题并尝试了一些不同的方法。这将让它调整事件的大小以触发,但不会设置高度或宽度:

window.dispatchEvent(new Event('resize'));

不需要任何包含,只需使用它来代替:

heroEl.triggerEventHandler("window:resize", null); 

【讨论】:

【参考方案2】:

我遇到了同样的问题,我在 resize 事件触发的函数上使用 Spy 解决了它。因此,您可以这样做:

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

这会更清楚,因为您不需要建立局部变量来检测它是否被触发。 ;)

【讨论】:

以上是关于在 Angular 2 中测试由“(window:resize)”事件触发的函数的主要内容,如果未能解决你的问题,请参考以下文章

Angular 2.0.0 - 测试“由模块'DynamicTestModule'导入”

Angular2(TypeScript)中的单元测试/模拟窗口属性

如何使用 Javascript“查找”由 Angular 组件提供的元素?

如何在 AngularJS 单元测试中模拟 $window.location.replace?

Angular中的单元测试socket.io

由angular命令行工具(angular-cli)生成的目录和文件