Vinay
Vinay

Reputation: 962

Code Coverage issue when spyon is used

I am writing a unit test for my component(Angular2 app) using Karma-Jasmine. And I am making use of Istanbul for Code Coverage report.

Here is my test case,

it('Should Invoke onNext function', async(() => {
    const fixture = TestBed.createComponent(LoginComponent);
    fixture.detectChanges();
    const login = fixture.componentInstance;

    spyOn(login, 'onNext');

    let email = fixture.debugElement.nativeElement.querySelector("input[name='username']");
    email.value = "email";

    let nextButton = fixture.debugElement.nativeElement.querySelectorAll("button")[1];
    nextButton.click();

    fixture.whenStable().then(() => {
      expect(login.onNext).toHaveBeenCalled();
    })
  }));

As you can see I am spying on onNext function to verify whether it is getting called or not on nextbutton click. It is working fine and the test passes.

But the code coverage report for my Login page shows that the onNext function is not covered. enter image description here

What am I doing wrong??

And also if I don't spy on onNext function, the function is covered,

it('Should Invoke onNext function', async(() => {
    const fixture = TestBed.createComponent(LoginComponent);
    fixture.detectChanges();
    const login = fixture.componentInstance;


    let email = fixture.debugElement.nativeElement.querySelector("input[name='username']");
    email.value = "email";

    let nextButton = fixture.debugElement.nativeElement.querySelectorAll("button")[1];
    nextButton.click();
  }));

enter image description here

Upvotes: 14

Views: 3914

Answers (1)

Robin Dijkhof
Robin Dijkhof

Reputation: 19288

Use this:

spyOn(login, 'onNext').and.callThrough()

Upvotes: 25

Related Questions