Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
});
like image 856
RyanP13 Avatar asked Dec 18 '22 21:12

RyanP13


1 Answers

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!

like image 111
danb Avatar answered Dec 28 '22 10:12

danb