I have a component as follows:
// 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--;
}
}
Following is specs file for above component:
// 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
})
})
I didn't understand why customerCount
variable has value 10 in both cases. It should have 11 and 9 value respectively stored for the specs. But, when I replace customerCount
with component.customerCount
, tests are run successfully. Can someone please help me why earlier approach is not updating local customerCount
variable with incremented and decremented value for respective tests.
question from:
https://stackoverflow.com/questions/65642881/initial-value-is-stored-in-the-variable-after-calling-angular-component-method-i 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…