lundi 19 octobre 2020

Angular: test service with other service and interface dependency

I'm trying to test a service and getting this error:

TypeError: Cannot read property 'apiUrl' of undefined

This is the service I'm testing:

proyectos.service.ts

import { ConfiguracionService } from './configuracion/configuracion.service';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
// other imports deleted...

@Injectable({
   providedIn: 'root',
})
export class ProyectosService {
   protected basePath: string;
   public respuesta = new HttpResponse();

   constructor(
      protected httpClient: HttpClient
      ){
      this.basePath = ConfiguracionService.configuracion.apiUrl;
      }

   public obtenerTiposProyecto(): Observable<any> {
      const headers: HttpHeaders = ObtenerCabeceras();

This service has a dependency on this other service:

configuracion.service.ts

import { environment } from '../../../environments/environment';
import { HttpClient } from '@angular/common/http';
import { IConfiguracion } from './configuracion';
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ConfiguracionService {

  static configuracion: IConfiguracion;

  constructor(private http: HttpClient) { }

  cargar(): Promise<void> {

And this last service has a dependency on this interface:

configuracion.ts

export interface IConfiguracion {
    env: {
        name: string;
    };
    aad: {
        inquilino: string;
        cliente: string;
        ambito: string;
        urlRedireccionLocal: string;
    };
    apiUrl: string;
}

The test code is:

proyectos.service.spec.ts

import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ProyectosService } from './proyectos.service';
import { TestBed } from '@angular/core/testing';

fdescribe('ProyectosService', () => {
   let httpClient: HttpClient;
   let httpTestingController: HttpTestingController;
   let service: ProyectosService;

   beforeEach(() => {

      TestBed.configureTestingModule({
         imports: [HttpClientTestingModule],
         providers: []
  }).compileComponents();

  httpClient = TestBed.inject(HttpClient);
  httpTestingController = TestBed.inject(HttpTestingController);
  service = TestBed.inject(ProyectosService);
  });

   it('should be created', () => {
      expect(service).toBeTruthy();
   });

});

I'm new in this Angular world and this is giving me many headaches.

Hope anyone can help me to solve this.

Thanks in advance for your help.

Aucun commentaire:

Enregistrer un commentaire