Sayantan Banerjee
Sayantan Banerjee

Reputation: 93

Angular Unit Testing for HostListener (Window Resize)

I have a component file that has below code

@HostListener('window:resize', ['$event'])
onResize(event) {
    this.width = event.target.innerWidth;
}

I want to test it. I have tried with the below code in my spec file.

window.dispatchEvent(new Event("resize");
expect(component.onResize).toHaveBeenCalled();

but it is not working. Any help will be appreciated.

Upvotes: 3

Views: 3069

Answers (1)

Krunal Shah
Krunal Shah

Reputation: 864

I had the same problem and I solved using a Spy on the function triggered by the resize event.

 it('should trigger onResize method when window is resized', () => {
    const spyOnResize = spyOn(component, 'onResize');
    window.dispatchEvent(new Event('resize'));
    expect(spyOnResize).toHaveBeenCalled();
 });

Hope it helps!

Upvotes: 4

Related Questions