简体   繁体   中英

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.

You will have to create the event you are listening to, before using the SpyOn method. (In the following example it's a 'click' event). 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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