我有一个组件:
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();
}
}
并为stopTimer()
函数编写了一些测试,但是当我运行具有覆盖率的测试时,它们根本不会覆盖它,并且也不会损坏
这是我的代码:
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();
});
答案 0 :(得分:1)
之所以没有涵盖它,是因为当您spyOn
使用一种方法时,您会丢失其实现详细信息,而只是获得一个“ API”,您可以在其中查看是否调用了该方法。要不丢失实施细节,请使用.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();
});