Carolina
Carolina

Reputation: 250

Unit test doesn't cover code at all (Karma)

I have a component:

export class StopwatchComponent implements OnInit {
  hours = '00';
  minutes = '00';
  seconds = '00';
  isPaused = true;
  isStarted = true;
  num = 0;
  @ViewChild('waitBtn', {read: ElementRef}) waitBtn: ElementRef;

  stopTimer() {
    (this.hours = '00'), (this.minutes = '00'), (this.seconds = '00');
    this.num = 0;
    this.timerService.stop();
    this.isStarted = true;
    this.isPaused = true;
    this.timer.unsubscribe();
  }
}

And wrote some tests for stopTimer() function but when I run test with coverage they don't cover it at all, and don't broke either Here's my code:

it('should create', () => {
    expect(component).toBeTruthy();
  });

  it(`should create all parameters`, () => {          //works
    const fixture = TestBed.createComponent(StopwatchComponent);
    const header = fixture.componentInstance;
    expect(header.hours).toEqual('00');
    expect(header.minutes).toEqual('00');
    expect(header.seconds).toEqual('00');
    expect(header.isPaused).toEqual(true);
    expect(header.isStarted).toEqual(true);
    expect(header.num).toEqual(0);
    fixture.debugElement.query(By.css('#waitBtn'));
  });

 it('should call stopTimer', () => {          //don't
    const mockSpyStopTimer = spyOn(component, 'stopTimer');
    fixture.detectChanges();
    component.stopTimer();
    expect(component.hours).toEqual('00');
    expect(component.minutes).toEqual('00');
    expect(component.seconds).toEqual('00');
    expect(component.num).toEqual(0);
    expect(component.isStarted).toBeTruthy();
    expect(component.isPaused).toBeTruthy();
    expect(mockSpyStopTimer).toHaveBeenCalled();
  });

Upvotes: 0

Views: 95

Answers (1)

AliF50
AliF50

Reputation: 18889

The reason why it's not covering is because when you spyOn a method, you lose its implementation details and you just get an "API" where you can see whether it was called or not. To not lose the implementation details, use .and.callThrough().

it('should call stopTimer', () => { 
    // now every time stopTimer is called, we have its original implementation details         
    const mockSpyStopTimer = spyOn(component, 'stopTimer').and.callThrough(); // change this line
    fixture.detectChanges();
    component.stopTimer();
    expect(component.hours).toEqual('00');
    expect(component.minutes).toEqual('00');
    expect(component.seconds).toEqual('00');
    expect(component.num).toEqual(0);
    expect(component.isStarted).toBeTruthy();
    expect(component.isPaused).toBeTruthy();
    expect(mockSpyStopTimer).toHaveBeenCalled();
  });

Upvotes: 1

Related Questions