【问题标题】:angular mouse enter unit test is not working角鼠标进入单元测试不起作用
【发布时间】:2018-03-09 10:55:20
【问题描述】:

我正在尝试在 Angular 4 业力单元测试中测试鼠标输入,没有错误但鼠标输入没有调用绑定到鼠标输入事件的方法。

  <div class="contacts-content row no-gutters justify-content-between"
       (mouseover)="onMouseEnter($event)"
       (mouseout)="onMouseLeave($event)"
       (click)="click()"
       [ngClass]="{'edit': hover}">

  </div>

在组件类中我调用下面的方法

  onMouseEnter(event: any) {
    this.hover = true;
    this.elementRef.nativeElement.addClass = 'edit';
  }

  onMouseLeave(event: any) {
    this.hover = false;
    this.elementRef.nativeElement.addClass = 'un-edit';
  }

测试鼠标输入:

  it('should mouse over show the edit options to the user', () => {
    const div = fixture.nativeElement.querySelector('.contacts-content');
    const event = new Event('mouseenter');
    div.dispatchEvent(event);
    expect(component.hover).toBeTruthy('true');
    expect(fixture.nativeElement.querySelector('.col-1').getAttribute('display')).toBeTruthy('inline-block !important');
  });

在我的测试中,我试图调用鼠标输入事件,但预期的结果不匹配。当我看到代码覆盖率时,甚至没有调用该方法。

有什么想法吗?

【问题讨论】:

  • 为什么不mouseoverconst event = new Event('mouseover');
  • 我可以试试,但是实际的组件是在 mouseenter 上调用的,所以测试鼠标进入
  • 它将与mouseover一起使用
  • 我能够使用 debugEl.triggerEventHandler('mouseenter', {}); 获得 mouseenter / mouseleave 指令。就我而言,我需要使用debugEl = fixture.debugElement.query(By.directive(MyDirectiveClass));,并且该指令具有@HostListener('mouseenter') myHandler() { }

标签: angular angular-unit-test angular-test


【解决方案1】:

尝试使用 triggerEventHandler:

it('should mouse over show the edit options to the user', fakeAsync(() => {
    ...
    div.triggerEventHandler('mouseenter', {});
    tick();
    fixture.detectChanges();
    expect(fixture.nativeElement.querySelector('.col-1').getAttribute('display')).toEqual('inline-block !important');
}));

或者您可以使用真实的鼠标事件附加到目标元素:

it('should mouse over show the edit options to the user', fakeAsync(() => {
        const div = fixture.debugElement.query(By.css('.contacts-content'));
        let event = new MouseEvent('mouseenter', {
            bubbles: true,
            cancelable: true,
            view: window
        });
        div.nativeElement.dispatchEvent(event);
        tick();
        fixture.detectChanges();
        expect(fixture.nativeElement.querySelector('.col-1').getAttribute('display')).toEqual('inline-block !important');
    }));

【讨论】:

  • 请注意:.triggerEventHandler() 不需要与fakeAsync()tick() 一起使用(也可能不是fixture.detectChanges(),但可能取决于你在做什么在指令中)。
猜你喜欢
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 2019-06-05
  • 2021-01-07
  • 1970-01-01
  • 2017-04-08
相关资源
最近更新 更多