Angular2 单元测试鼠标事件

Angular2 Unit Test Mouse Events

我想测试一种在模态 Window 容器外关闭时有助于关闭模态 Window 的方法。

组件方法

public hide(): void {
    this.visibleAnimate = false;
    setTimeout(() => { this.visible = false; }, 200);
  }

public onModalClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('dialog-container')) {
      this.hide();
    }
  }

单元测试

it('should call hide method', fakeAsync(() => {
    component.hide();
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(component.visible).toEqual(false);
      tick(200);
      expect(component.visibleAnimate).toEqual(false);
    });
  }));



it('should call onModalClicked()', () => {
    const mockEvent = new Event('click'); --> Error
    component.onModalClicked(mockEvent);
    console.log(component.visible);
  });

我的单元测试在 hide() 方法上运行良好,如果我以正确的方式进行,请告诉我。

但我真的不知道如何测试 onModalClicked() 方法,因为它需要 MouseEvent 作为参数。

In my unit testing method, Event and MouseEvent mismatch error occurs, which is obviouse biut how to cover this method?

实际上不需要成为一个MouseEvent,只需要quack like one。因此,您可以制作一个符合要求的虚拟对象并将其转换为 MouseEvent 以使其适合您的方法参数类型。例如:

function createMouseEvent(hasClass, clazz): MouseEvent {
  const event = { target: { classList: { contains: (arg) => false } } }
  if (hasClass) {
    event.target.classList.contains = (cls) => {
      expect(cls).toBe(clazz)
      return true
    }
  } 
  return <any>event;
}

那就来测试吧,不需要实际测试能见度。这就是 hide 方法的工作(改变可见性)。您只想测试 onModalClickedbehavior,即根据包含 class 的元素调用 hide 或不调用 hide。所以你可以在 hide 函数上 spy,然后检查它是否被调用。

it('onModalClicked() should call hide() when element contains class', () => {
  spyOn(component, 'hide')
  const event = createMouseEvent(true, 'dialog-container');
  component.onModalClicked(event);

  expect(component.hide).toHaveBeenCalled()
})

it('onModalClicked() should NOT call hide() when element DOES NOT contain class', () => {
  spyOn(component, 'hide')
  const event = createMouseEvent(false, null);
  component.onModalClicked(event);

  expect(component.hide).not.toHaveBeenCalled()
})