Home > Software design >  TypeError: Cannot read properties of undefined (reading 'baseURL')
TypeError: Cannot read properties of undefined (reading 'baseURL')

Time:07-22

dailyplanningservice.ts

import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import { AppConfigService } from 'src/app/services/config/app-config.service';

import { Observable,} from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { RequisitionProposalPostModel } from '../model/requisition-proposal';
var jsonData = './assets/data/test.json';

interface JsonResponse {
  status: number;
  message: any;
  data: object;
  dataList:Array<any>;
}

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


  private handleResponse(response: JsonResponse) {
    return response;
  }

  serviceBase = "";
  baseUrl = "";
  constructor(private _http: HttpClient,
    private configService: AppConfigService) {

    this.baseUrl = this.configService.getConfig().baseURL;
    this.serviceBase = this.configService.getConfig().serviceBase;
  }

  getReportData(imoCode: string) {
    return this._http.get<any>(this.baseUrl   this.serviceBase   `dailyplan/noonReport?imoCode=`   imoCode);
  }

  getVesselData(imoCode: string) {   
    return this._http.get(this.baseUrl   this.serviceBase   `dailyplan/vesselCard?imoCode=`   imoCode);
  }

  getVesselCardData(imoCode: any): Observable<Object> {
    return  this._http.get(this.baseUrl   this.serviceBase   `dailyplan/port?imoCode=`   imoCode)
  } 

  submitrfqProposal(requisitionProposalPostModel: RequisitionProposalPostModel): Observable<any> {
    return this._http.post<any>( this.baseUrl   this.serviceBase   'dailyplan/requisition', requisitionProposalPostModel);
  }

  getRequisitionProposal(imoCode:any, voyageId:any): Observable<any> {

    return this._http.get<any>(this.baseUrl   this.serviceBase   `dailyplan/requisitionproposal?imoCode=`   imoCode  "&voyagePassageId=" voyageId);

 


  }


  // public getVesselData1(imoCode: any) {
  //   return this.http.get(this.baseUrl   this.serviceBase   `dailyplan/vesselCard?imoCode=`   imoCode).pipe(
  //     catchError(
  //       (error: HttpErrorResponse, caught: Observable<HttpEvent<unknown>>) => {
  //         console.error(
  //           'the component has caught an error, process it here',
  //           error
  //         );
  //         this.error = error;
  //         return of();
  //       }
  //     )
  //   );
  // }


  doRequest(endpointURL: string,
    method: string, data?: any,
    parms?: any, headers?: HttpHeaders) {

    const httpOptions = {
      headers: headers ? headers : new HttpHeaders({
        'Content-Type': 'application/json',
      }),
      body: !data ? {} : JSON.stringify(data),
      parms: parms
    }

    return this._http
      .request<JsonResponse>(method, this.baseUrl   this.serviceBase   `${endpointURL}`, httpOptions)
      .pipe(
        map(response =>
          this.handleResponse(response))
      );


  }
}

.ts file

It seems that the default test case is not running because of the error cannot read properties of undefined. I tried to search that in .ts file but didn't find solution. And not only for this component but for every component it is giving the same error. Atleast the default tests should have run.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CognitoService } from 'src/app/modules/auth/cognito.service';
import { DailyplanningService } from 'src/app/modules/pages/daily-planning/service/dailyplanning.service';
import { CommonService } from 'src/app/services/common/common.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss'],
})
export class HeaderComponent implements OnInit {

  responseLst: any = [];
  dailyplanningURL = "";
  bell_icon: boolean = false;

  constructor(public router: Router,
    private _service: DailyplanningService,
    private common: CommonService,
    public cognitoService: CognitoService) {

    this.common.shareDailyPlaningURL.subscribe((res: any) => {
      this.dailyplanningURL = res;
    });


    this.common.shareVesselData.subscribe((res: any) => {
      if (res) {
        this.responseLst = res;
      } else {
        this.getVesselData();
      }

    });

  }

  userAdminUrlActive = "";
  loading: boolean = false;
  collapsed = true;

  ngOnInit(): void {
console.log();

  }

  
  toggleCollapsed(): void {
    this.collapsed = !this.collapsed;
  }


  goDashboard() {
    this.dailyplanningURL = '';
    this.isShowPopIn = false;
    this.router.navigate(['/pages/dashboard']);
  }

  changeUrl() {
    this.dailyplanningURL = '';
    this.isShowPopIn = false;
  }

  logout() {
    this.cognitoService.signOut();
    this.router.navigate(['/login']);
  }
  userAccountClick() {
    this.userAdminUrlActive = '/pages/useraccount';
    this.router.navigate(['/pages/useraccount']);
  }
  vesselMgtClick() {
    this.userAdminUrlActive = '/pages/vesselmanagement';
    this.router.navigate(['/pages/vesselmanagement']);
  }


  gotoDailyplanning(data: any) {
    this.isShowPopIn = false;
    sessionStorage.setItem("vesselData", JSON.stringify(data));

    this.router.navigateByUrl('/pages/dashboard')
      .then(() => this.router.navigate(['/pages/dailyplanning']));
    this.dailyplanningURL = '/pages/dailyplanning';
  }

  isShowPopIn = false;
  showdailyPlanning() {
    if (this.isShowPopIn) {
      this.isShowPopIn = false;
    } else {
      if (this.responseLst.length == 0) {
        this.getVesselData();
      }
      setTimeout(() => {
        this.isShowPopIn = true;
      }, 500);

    }
  }

  getVesselData() {
    try {
      this.loading = true;
      let apiURL = "useradmin/vessels?email="   sessionStorage.getItem('email')
      this.common.doRequest(apiURL, 'get').subscribe({
        next: (res: any) => {
          let result: any = res;
          this.responseLst = [];
          if (result) {
            if (result.status == 200) {
              result.dataList.forEach((item: any) => {
                let obj: any = new Object();
                Object.keys(item).forEach(function (key: string) {
                  if (item[key] == 0 || item[key] == null) {
                    obj[key] = "0";
                  } else {
                    obj[key] = item[key];
                  }

                });
                this.responseLst.push(obj);
                this.loading = false;
              });
            }
          }
        },
        error: (error: any) => {
          this.loading = false;
          console.log('Error in getVesselData:'   error);
        }
      });
    } catch (error: any) {
      this.loading = false;
      console.log('Error in getVesselData:'   error.message);
    }

  }


  
}

spec.ts file

import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { HeaderComponent } from './header.component';

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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule,
                HttpClientTestingModule],
      declarations: [ HeaderComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();
  });

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

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

error message

TypeError: Cannot read properties of undefined (reading 'baseURL')
TypeError: Cannot read properties of undefined (reading 'baseURL')
    at new DailyplanningService (http://localhost:9876/_karma_webpack_/webpack:/src/app/modules/pages/daily-planning/service/dailyplanning.service.ts:32:50)
    at Object.DailyplanningService_Factory [as factory] (ng:///DailyplanningService/ɵfac.js:4:10)
    at R3Injector.hydrate (http://localhost:9876/_karma_webpack_/vendor.js:256012:35)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/vendor.js:255831:33)
    at NgModuleRef.get (http://localhost:9876/_karma_webpack_/vendor.js:266387:33)
    at Object.get (http://localhost:9876/_karma_webpack_/vendor.js:266064:35)
    at lookupTokenUsingModuleInjector (http://localhost:9876/_karma_webpack_/vendor.js:247913:39)
    at getOrCreateInjectable (http://localhost:9876/_karma_webpack_/vendor.js:248025:12)
    at ɵɵdirectiveInject (http://localhost:9876/_karma_webpack_/vendor.js:258951:12)
    at NodeInjectorFactory.HeaderComponent_Factory [as factory] (ng:///HeaderComponent/ɵfac.js:4:81)

CodePudding user response:

You have several dependencies invoked from your component.

HeaderComponent
      |  
      V
DailyplanningService
      |  
      V
AppConfigService
      |  
      V
?????????? (perhaps next dependencies)

So error is thrown from AppConfigService service after calling this.configService.getConfig() method from the DailyplanningService constructor.

That way you would have to mock AppConfigService instance from the providers array. Perhaps you have to mock more things, but from code, now I can only see the getConfig method has to be mocked.

beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule,
                HttpClientTestingModule],
      providers: [
         {
            provide: AppConfigService,
            useValue: {
                getConfig: () => ({ 
                  baseUrl: 'dummy-url',
                  serviceBase: 'api-base'
                })
            }
         }
      ],
      declarations: [ HeaderComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    .compileComponents();
});
  • Related