Error: Attempting to access property 'prod_id' of an undefined variable

Hi there, I'm encountering an issue and would appreciate some assistance. I need to test a function as shown in the code snippet below:


populateForm() {
    this.activatedRoute.params.subscribe(
      params => {
        this.ws.getbyid(params['id']).subscribe(
          prod=> {
            this.prod= prod;
            this.editprodForm.controls['prodnr'].setValue(prod.prodnr);
            this.editprodForm.controls['proddesc'].setValue(prod.proddesc);
          }
        );
      }
    );
  }
  
  onupdatprod() {
    this.areWeWaiting = true;
    let updatprod= new Prod(this.editprodForm.value);
    updatprod.prod_id= this.prod.prod_id;

    this.ws.update(updatprod).subscribe(
      result => {
        if (result === true) {
          Materialize.toast('success', 4000);
        } else {
        }
      },
      error => {
      }
    );
  }

I have prepared the following testing code :


it('should call service.Updatewhen onupdateprod, Validation Error', done => {
    const mock = [];
    spyOn(component['as'], 'UpdateAlarms').and.callThrough()
    let updateprod = new Prod('1231');
    updateprod.prodnr= '4';
    updateprod.proddesc= 'UpdateTest';
    updateprod.prod_id= '1';
    component['ws'].update(updateprod ).subscribe(fail => {
        console.log('Validation Error')
        console.log(fail)
        expect(fail).toBeFalsy();
        done();
    });
    component.onupdatprod();
})

The error message I am receiving is:

TypeError: Cannot read property 'prod_id' of undefined

This error could be due to the fact that I'm trying to access `prod_id` which I get from `getbyid`, however, in the function `onupdatprod()` I attempt to set it using `updatprod.prod_id= this.prod.prod_id;`

If you have any suggestions or ideas on how to properly read the value of `prod_id`, please let me know.

Thanks for your help!

Answer №1

The function onUpdateProduct makes use of the variable this.product:

updateProduct.productId = this.product.productId;

However, the variable this.product is initialized within the function initializeForm:

this.product = product;

In your testing scenario, you are calling onUpdateProduct without calling initializeForm. As a result, when onUpdateProduct attempts to access this.product, it is undefined.

To address this issue, ensure that you include a call to initializeForm in your testing code so that this.product is properly defined.

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

Configuring Storybook to utilize typescript props with react-docgen-typescript-loader

I'm attempting to utilize react-docgen-typescript-loader for generating documentation of my props in Storybook using TypeScript Props. Unfortunately, I am facing an issue where the withInfo addon is not displaying any information. I am working with t ...

Retrieving data from a simulated angular service and making calls accordingly

I'm struggling with writing tests for a controller method that relies on an Angular service call and needs to test the code inside the .then() function afterwards. Here's the basic concept: // Controller $scope.myMethod = function() { meth ...

Having trouble with passing data using @Input in Angular 5

My goal is to pass a value from app.component.ts named user and assign it to the property of the userComponent called user. Below are the code snippets: app.component.ts import { Component } from '@angular/core'; @Component({ selector: &apo ...

Having trouble receiving a response from the websocket using RxJS in Node.js with Angular

Currently experimenting with setting up a WebSocket using rxjs webSocket I have managed to create a node server without any errors, but it is not sending messages to the server or connected users When I switch to 'ws://echo.websocket.org/', I c ...

Angular will move the input field cursor to the beginning after typing 4 digits

I'm looking for some guidance with a specific scenario involving a reactive form input field. The field is meant to capture the last four digits of a Social Security Number (SSN), and upon filling it out, an API call is triggered to validate the enter ...

Utilizing ngModel, struggling to properly implement the Required validator

I seem to be running into issues with the Required ngModel validation in my Angular project. The front-end user isn't being notified that they haven't entered anything in the form even though I'm using Bootstrap along with Angular/Typescript ...

The Angular service uses httpClient to fetch CSV data and then passes the data to the component in JSON format

I'm currently working on an Angular project where I am building a service to fetch CSV data from an API server and convert it to JSON before passing it to the component. Although the JSON data is successfully logged in the console by the service, the ...

What is the best approach to utilizing directives across multiple modules within Angular?

Recently, I created a directive called uppercase-input.directive.ts I attempted to import and use this directive in multiple components, but encountered the following error I have only shared one file here (organization.module.ts), but there are several ot ...

Personalize your classes in angular 8

I am looking to dynamically create classes with specific background colors fetched from a bank. Is there a way to achieve this in Angular? I have heard that @ViewChildren might be helpful in achieving this. These classes will be generated based on data re ...

How can I use a single route in Angular 5 to direct all paths for an outlet to a single component?

Here is my current setup: const routes: Routes = [ { path: '', component: NavComponent, outlet: 'nav' }, // (1) { path: '**', component: NavComponent, outlet: 'nav' } // (2) ]; The configuration is functioning ...

How Angular services transmit information to components

I have implemented a search field within my top-bar component and I am facing an issue in passing the input value of that search field to another component. Design Search service Top bar component Result component Operation Top bar component receives th ...

The Typescript ternary operation issue indicating that the condition is expected to always result in 'false'

I encountered a Typescript error that says: This condition will always return 'false' since the types 'TItem' and '"Chat"' have no common values. TS2367 Here is the code snippet causing the error: const { menu } = stat ...

Unpacking nested JSON objects with key-value pairs at various depths using TypeScript within a Node environment

Currently, I am faced with the task of parsing data at various levels in order to retrieve it while maintaining a consistent format. My project involves using TypeScript within the Node environment (specifically Google Cloud), and although I am relatively ...

Strange data being received by Angular from ASP.NET API

I'm encountering some trouble with my ASP.NET API communicating with Angular, and I'm unsure of the root cause. I'm seeking assistance in reviewing my code for any glaring errors. Here is a snippet from my API Controller: // Data Structure ...

What is the best way to access the first child element within props.children?

As a newcomer to React.js and Typescript, I am currently facing a challenge in extracting the first element from props.children. I have grasped that the parent component receives props.children as either React.element or an array of React.element[]. My g ...

Angular: The fetched data from the API is coming back as undefined

I am trying to use the Highcharts module in Angular to build a chart. The data object needed for the chart is provided by an API, and this is the structure of the object: { "success": true, "activity": [ { &q ...

Discover how to access and manipulate JSON files in an Angular application using

Currently, I am diving into learning TypeScript with Angular and I'm interested in reading a JSON file. The structure of my JSON file is as follows: { "nb": "7", "extport": "1176",, "REQ_EMAIL": ...

The server is currently active on port 80, but unfortunately cannot be accessed using the domain

I've successfully configured my Angular5 server to run, but I'm facing an issue. When I start it on port 80, I am unable to access it using [domain].de or ; only seems to work. Why is this happening? To initiate the server, I use the following ...

What is the approach to forming a Promise in TypeScript by employing a union type?

Thank you in advance for your help. I am new to TypeScript and I have encountered an issue with a piece of code. I am attempting to wrap a union type into a Promise and return it, but I am unsure how to do it correctly. export interface Bar { foo: number ...

What is the method for storing the values of a Select tag from react-select into a state?

I am currently facing an issue with setting values that I receive when selecting multiple items from a tag using "react-select". The state outcome I am looking for when selecting values from the tag should be: ['user._id', 'user._id', & ...