Bianca Alexiuc
Bianca Alexiuc

Reputation: 13

How Angular 9 unit test must be written?

I am new to Angular and it's very hard for me to understand how to write a unit test for a piece of code. Can someone please explain to me how to write a unit test for the following code?

toggleClassActive(station: any): void {
  this.isDisabled = false;
  this.stationsList.map((st) => {
    if (st.id === station.id) {
      st.active = true;
    } else {
      st.active = false;
    }
  });
}

Upvotes: 1

Views: 40

Answers (1)

Philipp Meissner
Philipp Meissner

Reputation: 5482

Given this example component

export class FooComponent {
  isDisabled = true;
  stationsList: Array<{ id: number, active: boolean }> = [
    {id: 1, active: false}, {id: 2, active: true},
  ];

  constructor() {
  }

  toggleClassActive(station: { id: number, active: boolean }): void {
    this.isDisabled = false;
    this.stationsList.map((st) => {
      if (st.id === station.id) {
        st.active = true;
      } else {
        st.active = false;
      }
    });
  }
}

Here's a unit test for that very method

import {TestBed} from '@angular/core/testing';
import {FooComponent} from './foo.component';

describe('FooComponent', () => {
  let component: FooComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        FooComponent,
      ],
    });

    component = TestBed.inject(FooComponent);
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should toggle active class', () => {
    // Optionally test the initial values // state
    expect(component.stationsList).toEqual([
      {id: 1, active: false}, {id: 2, active: true},
    ]);
    expect(component.isDisabled).toEqual(true);


    // Trigger the effect
    component.toggleClassActive({id: 1, active: false});


    // Assert the expected changes
    expect(component.stationsList).toEqual([
      {id: 1, active: true}, {id: 2, active: false},
    ]);
    expect(component.isDisabled).toEqual(false);
  });
});

Upvotes: 1

Related Questions