vendredi 26 juin 2020

Angular Testing - TypeError: Cannot read property '7' of undefined

I'm new to the Angular Testing and I'm trying to make this test work, but can't find a way to solve this. If anyone has any thoughts, please.

TypeError: Cannot read property '7' of undefined at at AnaliseContasTitularComponent.ngOnInit (http://localhost:9876/karma_webpack/src/app/extratos-mensais-interno/analise-contas-titular/analise-contas-titular.component.ts:103:2)

Executing this command to execute the test:

ng test --codeCoverage=true --progress=false --watch=false

My test unit file:

import { Overlay } from '@angular/cdk/overlay';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { InjectionToken } from '@angular/core';
import { MAT_DIALOG_SCROLL_STRATEGY, MatDialog } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { RouterTestingModule } from '@angular/router/testing';
import { AnaliseContasTitularComponent } from './analise-contas-titular.component';

import { ExtratosMensaisInternoService } from '../extratos-mensais-interno.service';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ RouterTestingModule, HttpClientTestingModule ],
      declarations: [ AnaliseContasTitularComponent ],
      providers: [ MatDialog, Overlay, MatSnackBar,
        { provide: InjectionToken, useValue: {} },
        { provide: MAT_DIALOG_SCROLL_STRATEGY, useValue: {} },
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AnaliseContasTitularComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  

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

the ngOnInit methor on the .ts file:

ngOnInit(): void {
    const competencia: CompetenciaInterno = this.serv.getCompetenciaSelecionada();

    this.serv.getExtratoMensal(competencia[7]).subscribe((res: ExtratoMensalData) => {
      this.extratoMensal = res.data;
    }, (error: HttpErrorResponse) => {
      this.utils.showDialogError(error);
    });

  }

And the service file, with the method that is called by the ngOnInit:

getCompetenciaSelecionada(): CompetenciaInterno {
    return JSON.parse(sessionStorage.getItem('competenciaInterno'));
  }

I can't find an example on the internet dealing with the mocking data in a way that works.

I just need to stop this error, because I have multiple files ocurring that same error. For me to proceed with other tests.

Thank you

Aucun commentaire:

Enregistrer un commentaire