veroneseComS
veroneseComS

Reputation: 768

My spy is being called but my function is not being covered in karma coverage

I have a sidenav component and inside i have a header component:

<div>
   <app-header id="header" (openSidenavEmitter)="openSidenav()"></app-header>
</div>

My header component have a event emitter that when the user click in the hamburg icon, it emits a event to parent component to open the sidenav:

@Output() openSidenavEmitter = new EventEmitter();
openSidenav() {
   this.openSidenavEmitter.emit()
}

In my sidenav component, when i receive this event, i call a function openSidenav() to set true to variable showSidenav:

openSidenav() {
   this.showSidenav = true;
}

I'm trying to make a unit test that cover the function openSidenav(). My spy is being called, my test is passing but my function is still not be covering in karma coverage report. This is my test:

it('should open sidenav when user click in hamburg icon', () => {
   const spyOnOpenSidenav = spyOn(component, 'openSidenav')
   const header = fixture.debugElement.query(By.css('#header'));
   header.triggerEventHandler('openSidenavEmitter', {});
   fixture.detectChanges();
   expect(spyOnOpenSidenav).toHaveBeenCalled();
}

How i can cover this function?

Upvotes: 0

Views: 953

Answers (1)

IDK4real
IDK4real

Reputation: 1042

I would suggest updating your test to the following:

it('should open sidenav when user click in hamburg icon', () => {
   const spyOnOpenSidenav = spyOn(component, 'openSidenav').and.callThrough()
   ...
}

What may be happening is that you are calling your method, which has a spy on it. Because of the spy being placed on the method, it will not actually execute unless you tell it.

To ensure the method continues the execution you should use the and.callThrough() method.

Additionally, if you want to ensure your test is completly covering your function you check that the value of openSidenav changes to true.

This is a very simple function, but if you had more behaviour that could change the value of openSidenav you wouldn't know if the test was successfull without looking at the final value.

Upvotes: 1

Related Questions