Search code examples
angularjasmineangular-test

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


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.


Solution

  • return this.customerCount++; will always return the value of this.customerCount before incrementing it.

    To make it work with the local variable, you can use the prefix increment/decrement operator:

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