Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing the function triggered by the "(window:resize)" event in Angular 2

I am attempting to test a function (with Karma) that is triggered by a window resize event. Everything works normally in the real world, but when I try to manually trigger the event in the test the function never gets called. This is resulting in a failed test.

Here is my HTML:

<div id="topnav" 
     class="navbar navbar-graylight header-width" 
     role="banner" 
     (window:resize)="onResize($event)"></div>

Here is my onResize() Function:

@Component({
  selector: "main-header",
  templateUrl: "main-header.component.html",
})
export class MainHeaderComponent {

  public itWasTriggered = false;

  public onResize(event) {
    this.itWasTriggered = true;
  }
}

Here is my Test:

it("Why is onResize() not being ran", () => { 
   const heroEl = fixture.debugElement.query(By.css(".navbar-graylight"));
   heroEl.triggerEventHandler("window:resize", null); 
   expect(comp.itWasTriggered).toBe(true);
});

This is what shows up in the inspector:

<div _ngcontent-a-1="" class="navbar navbar-graylight header-width" id="topnav" role="banner">
  <!--template bindings={}-->
  <!--template bindings={}-->
</div>
like image 994
ed-tester Avatar asked Nov 15 '16 18:11

ed-tester


People also ask

How do you fire a window resize event?

Try this: window. dispatchEvent(new Event('resize')); Hope it helps!!

What is the function of fixture detectChanges () in angular?

Fixtures have access to a debugElement , which will give you access to the internals of the component fixture. Change detection isn't done automatically, so you'll call detectChanges on a fixture to tell Angular to run change detection.

What is beforeEach in angular?

beforeEach is a global function in Jasmine that runs some setup code before each spec in the test suite. In this test suite, beforeEach is used to create a testing module using the TestBed object and declares any components that would be used in this testing module.


1 Answers

I had the same problem and I solved it using a Spy on the function triggered by the resize event. Thus, you could do something like this:

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

This would be a clearer as you wouldn't need to establish local variables to detect if it was triggered. ;)

like image 73
Анна Avatar answered Sep 18 '22 07:09

Анна