pop
pop

Reputation: 3714

Angular2 + Jasmine Event Object

I have this simple method which needs to be tested:

  public onLayerContainerClick(event: Event): void {
    event.stopPropagation();
    event.preventDefault();
    if (event.srcElement.classList.contains('dpm-info__layerContainer')) {
     this.closeInfoLayer(event);
    }
  }

My objective is actually to increase code coverage for the component. If I test is like this:

  it( 'should close on info container click', () => {
    spyOn( component, 'onLayerContainerClick' );
    const el: DebugElement = fixture.debugElement.query( By.css( '.dpm-info__layerContainer' ) );
    el.triggerEventHandler( 'click', null );
    expect( component.onLayerContainerClick ).toHaveBeenCalled();
  } );

the test is OK, but instanbul says "function not covered". So I guess, I need to call the function explicitly? To do that, I need to have a full event object, including (at least) srcTarget property. How do I define such an event within the unit test?

Upvotes: 1

Views: 4925

Answers (2)

pop
pop

Reputation: 3714

Thanks to estus and DrNio I've come up with this test, which makes istanbul code coverage happy and doesn't have any type problems:

  it( 'should close on info container click', () => {
    spyOn( component, 'closeInfoLayer' );
    const el: HTMLElement = fixture.debugElement.query(By.css('.dpm-info__layerContainer')).nativeElement;
    const mockEvent: Event = <Event><any>{
      srcElement: {
        classList: el.classList
      },
      stopPropagation: <any>( ( e: any ) => { /**/ }),
      preventDefault: <any>( ( e: any ) => { /**/ }),
    };

    component.onLayerContainerClick( mockEvent );
    expect( component.closeInfoLayer ).toHaveBeenCalled();
  } );

Upvotes: 1

DrNio
DrNio

Reputation: 1976

You have to call the function with a mocked event in the test. component.onLayerContainerClick({ srcElement: { value: 'mock_value' } });

And then write what you expect

expect( component.closeInfoLayer ).toHaveBeenCalled();

Maybe this https://angular.io/guide/testing#triggereventhandler might help as well

Upvotes: 3

Related Questions