Error: Issue with accessing the 'get' property of an undefined value (Resolved issue with incompatible imports not functioning)

Encountering an issue while attempting to execute the karma TS spec file. Despite all modules and imports functioning properly without conflicts, the error persists. I've tried incorporating component.ngOninit() into beforeEach() and it(), but to no avail. The problem seems to be linked to potential clashes such as HttpClientTestingModule import or conflicting providers/declarations. Regrettably, the source of the error, which reads "TypeError: Cannot read property 'get' of undefined," remains unidentified, preventing the successful passage of this spec file.

Spec File

import {async, ComponentFixture, TestBed} from '@angular/core/testing';

import {AcaPersonComponent} from './aca-person.component';
import {
  MatCardModule, MatDividerModule,
  MatFormFieldModule,
  MatIconModule,
  MatInputModule,
  MatOptionModule,
  MatRadioModule,
  MatSelectModule
} from '@angular/material';
import {ReactiveFormsModule} from '@angular/forms';
import {MFGDatePickerModule} from 'mfg-datepicker';
import {TextMaskModule} from 'angular2-text-mask';
import {AppRoutingModule} from '../../../../../app-routing.module';
import {HttpClientTestingModule} from '@angular/common/http/testing';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {LandingPageComponent} from '../../../../../landing-page/landing-page.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AcaPersonComponent,
        LandingPageComponent],
      imports: [MatFormFieldModule,
        ReactiveFormsModule,
        MatIconModule,
        MatInputModule,
        MFGDatePickerModule,
        MatOptionModule,
        MatSelectModule,
        MatRadioModule,
        MatCardModule,
        TextMaskModule,
        AppRoutingModule,
        BrowserAnimationsModule,
        HttpClientTestingModule,
        MatDividerModule
      ]
    })
      .compileComponents();
  }));

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

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

Error

TypeError: Cannot read property 'get' of undefined
    error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 33669121, rootNodeFlags: 33554433, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 33554433, childFlags: 114688, directChildFlags: 114688, childMatchedQueries: 0, matchedQueries: Object({  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 1, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: '', name: 'app-aca-person', attrs: [  ], template: null, componentProvider: Object({ nodeIndex: 1, parent: <circular reference: Object>, renderParent: <circular reference: Object>, bindingIndex: 0, outputIndex: 0, checkIndex: 1, flags: 114688, childFlags: 0, directChildFlags: 0, childMatchedQueries: 0, matchedQueries: Object, matchedQueryIds: 0, references: Object, ngContentIndex: -1, childCount: 0, bindings: Array, bindingFlags: 0, outputs:  ...
        at <Jasmine>
        at AcaPersonComponent.get type [as type] (http://localhost:9876/_karma_webpack_/src/app/aca/aca-stepper/aca-steps/aca-step-2/aca-person/aca-person.component.ts:70:28)
        at AcaPersonComponent.ngOnInit (http://localhost:9876/_karma_webpack_/src/app/aca/aca-stepper/aca-steps/aca-step-2/aca-person/aca-person.component.ts:24:14)
        at checkAndUpdateDirectiveInline (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:31909:1)
        at checkAndUpdateNodeInline (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:44366:1)
        at checkAndUpdateNode (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:44305:1)
        at debugCheckAndUpdateNode (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:45327:36)
        at debugCheckDirectivesFn (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:45270:1)
        at Object.eval [as updateDirectives] (ng:///DynamicTestModule/AcaPersonComponent_Host.ngfactory.js:7:5)
        at Object.debugUpdateDirectives [as updateDirectives] (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:45258:1)
        at checkAndUpdateView (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:44270:1)
    TypeError: Cannot read property 'get' of undefined
        at <Jasmine>
        at AcaPersonComponent.get type [as type] (http://localhost:9876/_karma_webpack_/src/app/aca/aca-stepper/aca-steps/aca-step-2/aca-person/aca-person.component.ts:70:28)
        at AcaPersonComponent.ngOnInit (http://localhost:9876/_karma_webpack_/src/app/aca/aca-stepper/aca-steps/aca-step-2/aca-person/aca-person.component.ts:24:14)
        at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/aca/aca-stepper/aca-steps/aca-step-2/aca-person/aca-person.component.spec.ts:58:15)
        at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:365:1)
        at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:305:1)
        at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
        at Zone.run (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:124:1)
        at runInTestZone (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:554:1)
        at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:569:1)
        at <Jasmine>

TS Class

import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormGroup, Validators} from '@angular/forms';
import {merge} from 'rxjs';

@Component({
  selector: 'app-aca-person',
  templateUrl: './aca-person.component.html',
  styleUrls: ['./aca-person.component.css']
})
export class AcaPersonComponent implements OnInit {

  @Input() personType: string;
  @Input() peopleForm: FormGroup;
  @Input() nextWasClicked: boolean;
  @Input() index: number;
  @Output() removePerson = new EventEmitter<boolean>();
  cardTitle: string;
  personAge: number;

  constructor() {
  }

  ngOnInit() {
    if (this.type.value == 'primary') {
      this.cardTitle = 'Your Information';
    } else if (this.type.value == 'spouse') {
      this.cardTitle = 'Spouse';
    } else if (this.type.value == 'dependent') {
      this.cardTitle = 'Dependent';
    }
    this.dobAndIsPregnantVC();
  }

  dobAndIsPregnantVC() {
    merge(
      this.dob.valueChanges,
      this.gender.valueChanges
    )
      .subscribe(() => {
        this.calculateAge(this.dob.value);
        if (this.gender.value == 'F') {
          this.is_pregnant.setValidators(Validators.required);
          if (this.personAge < 14) {
            this.is_pregnant.setValue(null);
            this.is_pregnant.clearValidators();
          }
        } else {
          this.is_pregnant.setValue(null);
          this.is_pregnant.clearValidators();
        }
        this.is_pregnant.updateValueAndValidity();
      });
  }

  // Calculate the age of the client from their birth date to display in the census details
  private calculateAge(date: string) {
    if (date) {
      const timeDiff = Math.abs(Date.now() - new Date(date).getTime());
      this.personAge = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
    }
  }

  onRemovePerson() {
    this.removePerson.emit(true);
  }

  // GETTERS

  get type() {
    return this.peopleForm.get('type');
  }

  get first_name() {
    return this.peopleForm.get('first_name');
  }

  get last_name() {
    return this.peopleForm.get('last_name');
  }

  get gender() {
    return this.peopleForm.get('gender');
  }

  get dob() {
    return this.peopleForm.get('dob');
  }

  get uses_tobacco() {
    return this.peopleForm.get('uses_tobacco');
  }

  get affordable_care() {
    return this.peopleForm.get('affordable_care');
  }

  get is_pregnant() {
    return this.peopleForm.get('is_pregnant');
  }


}

Answer №1

The reason this issue is occurring is because the test case lacks defined @Input. To rectify this, you should create it as demonstrated below:

  beforeEach(() => {
    fixture = TestBed.createComponent(AcaPersonComponent);
    component = fixture.componentInstance;
    component.peopleForm = fb.group({
       type:  ['Other Name', Validators.required],
       first_name: ['f_name', Validators.required],
       //.. and so on for all parameters
    });
    component.personType = 'Some Type';
    component.nextWasClicked = true;
    component.index = 1; // or any other required value
    fixture.detectChanges();
  });


This approach will assist in defining this.peopleForm, ensuring that lines like this.peopleForm.get('type'); do not result in such errors.

No necessity to include component.ngOnInit()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the significance of these specific HTML attributes within the button tag?

While browsing the web, I stumbled upon this HTML snippet: <button class="button--standard" mat-button mat-flat-button [disabled]=true >Disabled State</button> The combination of attributes like mat-button mat-flat-button [disabled]=true is u ...

What is the best way to pass dynamic values to a service constructor from a component?

After days of attempting to grasp 'the Angular paradigm', I still find myself struggling to understand something about services that are not singletons. It seems impossible for me to pass a runtime-determined value to a service constructor, as I ...

Implementing Role-Based Authentication in Angular 6

I am managing a project with 5 modules that require different levels of access (create, update, delete, view) based on user roles. I am using Angular 6 for the UI development and I need to set up role-based authentication. For instance, an admin should ha ...

Tips for setting up a hierarchical mat-table within a parent table that supports expandable rows using Angular Material

Here is the data that I am working with: [ { "_id": "c9d5ab1a", "subdomain": "wing", "domain": "aircraft", "part_id": "c9d5ab1a", "info.mimetype": "application/json", "info.dependent": "parent", ...

Creating Dynamic Graphs using Angular and Chart.js with Array Values

I have implemented ChartJS-2 to visualize a graph displaying an array of user activities, but it appears distorted: import { Component, OnInit, Input } from '@angular/core'; import { ChartOptions, ChartType, ChartDataSets } from 'chart.js ...

The Angular application is currently building successfully, however when launched it displays a blank white screen. Upon checking the network tab

Seeking assistance as I am encountering a blank screen in the browser after debugging my Angular 15 application. The workspace does not exhibit any issues or errors. However, upon exploring the Network tab in DevTools, I observed that config.js, styles.css ...

An effective method for adding information to a REDIS hash

My current computing process involves storing the results in the REDIS database before transferring them to the main database. At the moment, I handle operations in batches of 10k items per chunk using a separate GAE instance (single-threaded computing wi ...

Strategies for Implementing Responsive Design in Angular and Bootstrap Shopping Cart Apps to Deliver Custom Views on Mobile and Desktop Devices

Our shopping cart application utilizes Angular and Bootstrap. We are in need of routing different pages for mobile and desktop screens. Specifically, we want the /cart route to display a different page on mobile devices compared to desktops, taking into ...

What is the necessity of Angular reflect polyfill for JIT mode?

I recently came across information on the Angular browser support page discussing the JIT compilation and the ES7/reflect polyfill, stating: It is possible to remove if you always utilize AOT and solely rely on Angular decorators. However, a couple of ...

type of key extractor is unknown in React Native

How can I specify a type for the renderItem function of a FlatList in React Native? This is my current approach: // Importing the generic type for the FlatList render item function import { ListRenderItem } from "react-native"; // Assigning the ...

Ways to prevent an array from being reset

My issue involves the clothes and orders tables, along with an array based on Clothes and Orders models. Whenever I add a clothes element into the Orders array and specifically update the amount and price of the selected item, it also updates the Clothes a ...

Unable to utilize Google Storage within a TypeScript environment

I'm encountering an issue while attempting to integrate the Google Storage node.js module into my Firebase Cloud functions using TypeScript. //myfile.ts import { Storage } from '@google-cloud/storage'; const storageInstance = new Storage({ ...

Discovering the true rendering elements in karma tests: A guide

Recently, I started working on a new project in Angular14. However, when I completed writing the unit tests, all I could see was a series of successful text information and not any HTML elements displayed. How can I view the HTML elements? ...

Dealing with 401 Unauthorized error and CORS issues in Angular POST requests to a .NET Core Web Api

My front-end and back-end projects are separate, using Angular for the front-end and .NET Core WEB Api for the back-end. I have successfully set up CORS and windows AD authentication. While GET calls work fine, I am experiencing issues with POST requests. ...

Having issues with using the class selector in SVG.select() method of the svg.js library when working with TypeScript

Exploring the capabilities of the svg.js library with typescript has presented some challenges when it comes to utilizing CSS selectors. My goal is to select an SVG element using the select() method with a class selector. In this interactive example, this ...

Using Angular 2, perform an HTTP GET request to retrieve data from a JSON file located in the assets folder

Currently, I am working on fetching data from a JSON file located in the assets folder of my application. The framework I am using is Angular Material. For this purpose, I have created an account component which consists of the following files: account.co ...

Incorporating a TypeScript interface into your Angular project

I recently started learning angular and I believe it's a good practice to include an interface in my code. The DataFetchService service is currently retrieving data from an internal .json file. Can someone guide me on the best approach to implement an ...

I'm looking to locate the API documentation for AngularJS TypeScript

After transitioning from using AngularJS 1.4 and plain JavaScript to now working with AngularJS 1.5 but utilizing TypeScript, I have found it challenging to find helpful documentation. For instance, when trying to inject services like $q or $timeout into m ...

Toggle the visibility of the navigation bar in Angular based on the user

I have implemented rxjs BehaviorSubject in my login page to transmit data to auth.service.ts, enabling my app.component to access the data stored in auth.service.ts. However, I now require the app.component to detect any changes made to the data in auth.se ...

Tips for modifying the width of the mat-header-cell in Angular

Is there a way to customize the mat-header-cell in Angular? I've been trying to change its width without success. Any suggestions would be greatly appreciated. <ng-container cdkColumnDef="name"> <mat-header-cell *cdkHeaderCellDe ...