测试由“(window:resize)"触发的函数;Angular 2 中的事件 [英] Testing the function triggered by the "(window:resize)" event in Angular 2

查看:26
本文介绍了测试由“(window:resize)"触发的函数;Angular 2 中的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这是我的 HTML:

这是我的 onResize() 函数:

@Component({选择器:主标题",templateUrl: "main-header.component.html",})导出类 MainHeaderComponent {public itWasTriggered = false;公共 onResize(事件) {this.itWasTriggered = true;}}

这是我的测试:

it("为什么 onResize() 没有被运行", () => {const heroEl = fixture.debugElement.query(By.css(".navbar-graylight"));heroEl.triggerEventHandler("window:resize", null);期望(comp.itWasTriggered).toBe(真);});

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

<div _ngcontent-a-1="" class="navbar navbar-graylight header-width" id="topnav" role="banner"><!--模板绑定={}--><!--模板绑定={}--></div>

解决方案

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

 it('调整窗口大小时应该触发onResize方法', () => {常量 spyOnResize = spyOn(组件, 'onResize');window.dispatchEvent(new Event('resize'));期望(spyOnResize).toHaveBeenCalled();});

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

I am attempting to test a function (with Karma) that is triggered by a window resize event. Everything works normally in the real world, but when I try to manually trigger the event in the test the function never gets called. This is resulting in a failed test.

Here is my HTML:

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

Here is my onResize() Function:

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

  public itWasTriggered = false;

  public onResize(event) {
    this.itWasTriggered = true;
  }
}

Here is my Test:

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

This is what shows up in the inspector:

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

解决方案

I had the same problem and I solved it using a Spy on the function triggered by the resize event. Thus, you could do something like this:

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

This would be a clearer as you wouldn't need to establish local variables to detect if it was triggered. ;)

这篇关于测试由“(window:resize)"触发的函数;Angular 2 中的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆