【问题标题】:How to test document clicks in unit tests in angular如何在角度的单元测试中测试文档点击
【发布时间】:2018-04-17 12:46:14
【问题描述】:

我们有一个下拉组件,它的下拉列表在任何外部点击时都会折叠。 这被实现为:

  @HostListener('document:click', ['$event'])
  public documentClick(event) {
    if (this.dropdownIsOpen && !event.clickedFromMe) {
      this.dropdownIsOpen = false;
    }
  }

如何测试此代码?在使用TestBed.createComponent时,似乎只创建了组件,并且它不在任何文档中,那么如何模拟该组件之外的点击?

【问题讨论】:

  • 同时发布测试代码

标签: angular testing


【解决方案1】:

使用document.dispatchEvent

 it('should handle document click', () => {
    component.dropdownIsOpen = true;
    document.dispatchEvent(new MouseEvent('click'));
    expect(component.dropdownIsOpen).toBe(false);
  });

【讨论】:

    【解决方案2】:

    文档中。

    随便用

    const compiled: HTMLElement = fixture.nativeElement;
    compiled.ownerDocument.dispatchEvent(new Event('click'));
    

    另一种方法是为在其模板中使用您的组件的测试组件创建一个固定装置,以及一些兄弟按钮,例如,然后单击该兄弟按钮。

    【讨论】:

      猜你喜欢
      • 2019-10-11
      • 2018-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      相关资源
      最近更新 更多