简体   繁体   English

将模拟DOM事件传递给Angular中的组件方法以进行单元测试

[英]Passing a mock DOM event to component method in Angular for unit testing

I am trying to test a method in one of my components as follows: 我试图在我的一个组件中测试一个方法如下:

toggle(event: Event): void {
    event.stopPropagation();
    this.isCollapsed = !this.isCollapsed;
}

I cannot find a way to pass the event object to the method in the unit test case for example: 我找不到将事件对象传递给单元测试用例中的方法的方法,例如:

test('it should call stop propagation when toggled', () => {
    testHostComponent.toggleLineBreakDown(mockEventGoesHere, 0);
});

You can test that preventDefault has been called via a Jasmine Spy. 您可以测试是否已通过Jasmine Spy调用preventDefault。

You will have to create the event you are listening to, before using the SpyOn method. 在使用SpyOn方法之前,您必须创建要监听的事件。 (In the following example it's a 'click' event). (在以下示例中,它是'click'事件)。 After creating the event and the spy, you will then need to dispatch the event to the element. 创建事件和间谍后,您将需要将事件分派给元素。

As an example: 举个例子:

const event = new MouseEvent('click'); 
spyOn(event, 'preventDefault');

element.dispatchEvent(event);
expect(event.preventDefault).toHaveBeenCalled();

Hopefully this helps! 希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM