在 Jasmine 中调用 Angular 组件方法后,初始值存储在变量中

Initial value is stored in the variable after calling Angular Component method in Jasmine

我有一个组件如下:

// customer-reservation.component.ts
import {Component} from "@angular/core";

@Component({
  selector: 'app-customer-reservation',
  template: ``
})
export class CustomerReservationComponent {
  customerCount = 10;

  registerCustomer() {
    return this.customerCount++;
  }

  unregisterCustomer() {
    return this.customerCount--;
  }
}

以下是上述组件的规格文件:

// customer-reservation.component.spec.ts
import {ComponentFixture, TestBed} from "@angular/core/testing";
import { CustomerReservationComponent } from "./customerReservation.component";

describe('Room Reservation', () => {
  let fixture: ComponentFixture<CustomerReservationComponent>;
  let component: CustomerReservationComponent;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        CustomerReservationComponent
      ]
    })

    // Set-up
    fixture = TestBed.createComponent(CustomerReservationComponent);
    component = fixture.componentInstance;

  })

  afterEach(() => {
    // Tear-down
    fixture = null;
    component = null;
  })

  it('Increase customer count in case of registration', () => {
    let customerCount: number;
    customerCount = component.registerCustomer();    // This is still 10
    expect(customerCount).toEqual(11);               // test fails

  })

  it('Decrease customer count in case of registration', () => {
    let customerCount: number;
    customerCount = component.unregisterCustomer(); // This is still 10
    expect(customerCount).toEqual(9);               // test fails
  })
})

我不明白为什么 customerCount 变量在这两种情况下的值为 10。它应该分别为规格存储 11 和 9 值。但是,当我将 customerCount 替换为 component.customerCount 时,测试成功 运行。有人可以帮助我为什么早期的方法没有更新本地 customerCount 变量,并为相应的测试增加和减少值。

return this.customerCount++; 在递增之前总是 return this.customerCount 的值。

要使其与局部变量一起工作,可以使用前缀 increment/decrement 运算符:

  registerCustomer() {
    return ++this.customerCount;
  }

  unregisterCustomer() {
    return --this.customerCount;
  }