13

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

Vinay
  • 952
  • 2
  • 10
  • 27
  • 1
    Because the spy actually replaces the function call. You have to make two tests : the first will test if the function is actually called (what you did), and the second will test your onNext function. –  Jul 04 '17 at 07:29
  • Didn't know that..Thanks for the info. Is there a better way to do that? such that I can achieve both at the same time? – Vinay Jul 04 '17 at 07:33
  • Yeah, put them both in the same `it` (although I wouldn't recommend that). By the way, calling `component.onNext()` will cover it in the code coverage, but it's not testing ! Testing means you have to use assertions to test if whether or not you get the correct values –  Jul 04 '17 at 07:34

1 Answers1

24

Use this:

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

Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116