vendredi 24 avril 2020

Angular - Jasmine - Reset and reload component

I want to spyOn a service more than once. To do that, I have used the jasmine.getEnv().allowRespy(true); statement.

When I do that, I figured out that I have to recreate my component in order for changes to take place. I do that with:

fixture = TestBed.createComponent(CardDisplayPageComponent);
component = fixture.debugElement.componentInstance;
fixture.detectChanges();

I end up having a code like this:

 it('should have a datasource when cache has data', () => {
    spyOn(cacheService, 'getFromCache').and.returnValue([CARD_GENERIC_DATA_MOCK]);

    fixture = TestBed.createComponent(CardDisplayPageComponent);
    component = fixture.debugElement.componentInstance;
    fixture.detectChanges();

    expect(component.dataSource).toBeTruthy();
  })


  it('should have a datasource when cache does not have data', () => {
    spyOn(cacheService, 'getFromCache').and.returnValue([undefined]);
    spyOn(seasonsFetchingService, 'getTransformedData').and.returnValue(of(CARD_PAGE_GENERIC_DATA_MOCK));

    fixture = TestBed.createComponent(CardDisplayPageComponent);
    component = fixture.debugElement.componentInstance;
    fixture.detectChanges();

    expect(component.dataSource).toBeTruthy();
  })

Is there a way to avoid this duplication?

Aucun commentaire:

Enregistrer un commentaire