我想测试一种方法,这些方法有助于在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 回答
它不需要实际上是
MouseEvent
,它只需要quack like one . 因此,您可以创建一个适合该帐单的虚拟对象并将其强制转换为MouseEvent
,以使其适合您的方法参数类型 . 例如:然后要测试它,您不需要实际测试可见性 . 这是
hide
方法的工作(更改可见性) . 您只想测试onModalClicked
的behavior
,它根据包含类的元素调用hide
或不调用hide
. 所以你可以在hide
函数上spy,然后检查它是否被调用 .