Angular Karma 测试:方法不会改变 class 属性?

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);
});

在该按钮上,使用参数 20 调用了单击方法 selectLastDays。应用程序工作得很好,那么为什么这个测试失败了?

您的第一个测试的问题是,您实际上在监视 selectLastDays 方法。仅使用 spyOn 将创建一个空存根,使该函数存在,但该函数不会执行任何操作。

如果您需要存根来验证方法被调用,那么您应该告诉存根实际执行函数。这是用 .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
});