RyanP13
RyanP13

Reputation: 7743

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

Upvotes: 4

Views: 21746

Answers (1)

danb
danb

Reputation: 356

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!

Upvotes: 14

Related Questions