[英]Angular Karma testing: method doesn't change class properties?
我很难理解为什么我的测试失败了。
Class 短:
export class Viewer implements OnChanges {
// ...
selectedTimePeriod: number;
timePeriods = [20, 30, 40];
constructor( /* ... */) {
this.selectLastDays(15);
}
selectLastDays(days: number): void { // happens on click
this.selectedTimePeriod = days;
// ...
}
}
HTML 短:
// ...
<ul>
<li *ngFor="let period of timePeriods">
<a [ngClass]="{'active': selectedTimePeriod === period}"
(click)="selectLastDays(period)">{{ period }} days
</a>
</li>
</ul>
测试短:
beforeEach(() => {
fixture = TestBed.createComponent(HistoryViewerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
dh = new DOMHelper(fixture);
});
it('should change selectedTimePeriod value to 20', async () => {
spyOn(component, 'selectLastDays');
dh.queryOne('li a').triggerEventHandler('click', null); // button value of 20
dh.queryOne('li a').nativeElement.click(); // clicked even twice
await fixture.whenStable();
fixture.detectChanges();
expect(component.selectLastDays).toHaveBeenCalledTimes(2); // <- true
expect(component.selectedTimePeriod).toEqual(20); // <- false
});
it('should change selectedTimePeriod', () => { // this test passes
expect(component.selectedTimePeriod).toEqual(15);
component.selectLastDays(20);
expect(component.selectedTimePeriod).toEqual(20);
});
在该按钮单击方法selectLastDays
使用参数20
调用。 应用程序工作得很好,为什么这个测试失败了?
您的第一个测试的问题是,您实际上监视了selectLastDays
方法。 仅使用 spyOn 将创建一个空存根,这使得 function 存在,但 function 不会做任何事情。
如果您需要存根来验证方法是否被调用,那么您应该告诉存根实际执行 function。 这是用.and.callThrough()
完成的
it('should change selectedTimePeriod value to 20', async () => {
spyOn(component, 'selectLastDays').and.callThrough(); // <= !!important
dh.queryOne('li a').triggerEventHandler('click', null); // button value of 20
dh.queryOne('li a').nativeElement.click(); // clicked even twice
await fixture.whenStable();
fixture.detectChanges();
expect(component.selectLastDays).toHaveBeenCalledTimes(2); // <- true
expect(component.selectedTimePeriod).toEqual(20); // <- false
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.