vendredi 15 janvier 2021

How do I test code inside ".subscribe()" Angular/Jasmine

I have this Code in my StatisticComponent

this.subscription = this.locationService.getStatisticOne(this.formService.getFormValue())
  .subscribe(data => {
    this.array = data;
    this.wrongValueOne = this.array.shift();
    for (let array of this.array) {
      this.addData(this.myChartOne, array.date, array.leistung);
    }
  });

Now I want to write a Test to see if anything inside this .subscribe() function is being called or executed. This code snippet is being executed inside a generateStatisticOne() function which is called in a getData() function which is called in ngOnInit() or at a button press. The problem is that im new to writing tests and don't even know if what I've found here makes even sense, but I have this code for the test for now

describe('StatisticComponent', () => {
  let component: StatisticComponent;
  let fixture: ComponentFixture<StatisticComponent>;

  const locationServiceSpy = jasmine.createSpyObj('LocationService', {
    getStatisticOne: of([{ id: 1 }, { id: 2 }, { id: 3 }])
  });


  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [StatisticComponent],
      imports: [
        HttpClientTestingModule
      ],
      providers: [{ provide: LocationService, useValue: locationServiceSpy },
        LocationService,
        HttpClientTestingModule
      ],
    })
      .compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(StatisticComponent);
    component = fixture.componentInstance;
    locationService = TestBed.get(LocationService);
    fixture.detectChanges();
  });

  it('should call array.shift ', fakeAsync(() => {
    const service = TestBed.get(LocationService); // get your service
    spyOn(service, 'getStatisticOne').and.callThrough(); // create spy
    spyOn(Array.prototype, 'shift');
    fixture.detectChanges();
    tick();
    expect(Array.prototype.shift).toHaveBeenCalled();
  }));

The error I get when running the code is "expected spy shift to have been called"

Aucun commentaire:

Enregistrer un commentaire