angular - 如何在 Angular 单元测试中测试文档点击

标签 angular testing

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

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

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

最佳答案

使用document.dispatchEvent:

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

关于angular - 如何在 Angular 单元测试中测试文档点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49878559/

相关文章:

javascript - Electron 应用程序中出现 Uncaught Error : Bootstrap's JavaScript requires jQuery at bootstrap. min.js :6,

Angular 与 spring mvc

angular - 如何修复错误 Error : Default pack is not registered in Nebular

performance - 如何在家做软件性能测试

c# - VS2010中的测试代码选项

Selenium 教程

angular - 为什么 Angular2(点击)事件没有在 <div> 上触发?

angular - 在 Angular 2 的 ng2-smart-table 的操作列中添加自定义按钮

ruby-on-rails - 如何为事件记录范围编写测试?

java - guava-teSTLib future 版本 JAR