Angular2 单元测试鼠标事件

Gag*_*ags 1 unit-testing karma-jasmine angular2-testing angular

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

组件方法

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();
    }
  }
Run Code Online (Sandbox Code Playgroud)

单元测试

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);
  });
Run Code Online (Sandbox Code Playgroud)

我的单元测试在hide()方法上运行良好,请让我知道我是否以正确的方式进行。

但我真的很困惑如何测试onModalClicked()方法,因为它以MouseEvent作为参数。

在我的单元测试方法中,发生 Event 和 MouseEvent 不匹配错误,这很明显,但如何覆盖此方法?

Pau*_*tha 5

它实际上并不需要一个MouseEvent,它只需要像一个 一样嘎嘎作响。因此,您可以制作一个符合要求的虚拟对象并将其转换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;
}
Run Code Online (Sandbox Code Playgroud)

然后要测试它,您不需要实际测试可见性。这就是hide方法的工作(改变可见性)。您只想根据包含类的元素测试 的behavioronModalClicked即它要么调用hide要么不调用。所以你可以监视这个hide函数,然后检查它是否被调用。

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()
})
Run Code Online (Sandbox Code Playgroud)