【问题标题】:Failed: Cannot read property 'click' of null in karma testing [closed]失败:在业力测试中无法读取 null 的属性“点击”[关闭]
【发布时间】:2020-11-03 11:00:12
【问题描述】:

我正在为 click 事件编写 karma/jasmine 测试用例,但我的按钮为空。请给我建议。提前致谢。

  it('should', async(() => {
    spyOn(component, 'clickMethod');
    let button = fixture.debugElement.nativeElement.querySelector('#view-rec');
    console.log(button); --> button is null I am getting
    button.click();
    fixture.whenStable().then(() => {
        expect(component.clickMethod).toHaveBeenCalled();
    })

组件::

  clickMethod() {
      this.msg.node.setVal(false);
      this.myBtn = "Hello";
  }

HTML::

<mat-menu #menu="matMenu" class="dropdown">
  <button mat-menu-item>
  </button>
  <button mat-menu-item id="view-rec"(click)='clickMethod()'>   
  </button> 
</mat-menu>

【问题讨论】:

  • 没有条件渲染,在 mat-menu 下拉菜单里面
  • 你可以试试这个:let button = fixture.debugElement.query(By.css('#view-rec'));
  • 你在访问 DOM 之前调用了 detectChanges 吗?

标签: javascript html angular typescript karma-jasmine


【解决方案1】:

我认为您需要先打开菜单,然后才能访问要单击的mat-menu-item

例如:

<button id="menu-open-icon" mat-icon-button [matMenuTriggerFor]="menu"> 
  <mat-icon>more_vert</mat-icon>
</button>

<mat-menu #menu="matMenu"> 
  <button mat-menu-item id="view-rec"(click)='clickMethod()'>
    <mat-icon>dialpad</mat-icon>
    <span>Redial</span>
  </button>
  <button mat-menu-item disabled>
    <mat-icon>voicemail</mat-icon>
    <span>Check voicemail</span>
  </button>
  <button mat-menu-item>
    <mat-icon>notifications_off</mat-icon>
    <span>Disable alerts</span>
  </button>
</mat-menu>

尝试:

it('should', () => {
    spyOn(component, 'clickMethod').and.callThrough();
    let menuIcon = fixture.debugElement.nativeElement.querySelector('#menu-open-icon')
    menuIcon.click();
    let button = fixture.debugElement.nativeElement.querySelector('#view-rec');
    console.log(button); --> this should not be null now
    button.click();
    fixture.detectChanges();
    expect(component.clickMethod).toHaveBeenCalled()
})

【讨论】:

  • @Vivek 谢谢,我明白了。
  • @Vivek,我可以通过 id="menu-open-icon" 获取按钮详细信息。但我无法获得 id="view-rec" 的按钮,因为 mat-menu 是从其他组件动态加载的。请建议我,如何获取动态加载按钮的详细信息。
  • @YYY :当然,您能否添加更多 HTML 代码以帮助我理解。另外,stackoverflow.com/questions/64678832/… 的任何 cmets 吗?
猜你喜欢
  • 2020-06-02
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
  • 2022-06-22
  • 2014-10-31
相关资源
最近更新 更多