首页 文章

Angular2单元测试鼠标事件

提问于
浏览
1

我想测试一种方法,这些方法有助于在Modal Window容器外部关闭时关闭模态窗口 .

Component Method

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();
    }
  }

Unit Test

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作为参数 .

在我的单元测试方法中,发生Event和MouseEvent不匹配错误,这是obviouse biut如何覆盖这个方法?

1 回答

  • 2

    它不需要实际上是 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 ,它根据包含类的元素调用 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()
    })
    

相关问题