Jasmine is raising an error: "TypeError: Unable to access the property 'client' of an undefined object"

While running test cases for the EditFlag component in Angular, I encountered an error stating TypeError: Cannot read property 'client' of undefined. Additionally, I am looking to add a test case for a switch case function. Can someone assist me with this particular test case?

editflag.component.ts

constructor(private flagService: FlagService,
private editFlagDialog: MatDialogRef<EditFlagComponent>),
@Inject(MAT_DIALOG_DATA) public data: any,
private dialog: MatDialog){}

ngOnInit: void {
    switch(this.data.action) {
        case 'create':
            this.flagClone = this.initializeFlagClone();
            break;
        case 'edit':
            this.flagEdit();
            break;
        default:
            console.log('No action');
    }
}

public flagEdit(){
    const res = {...this.data};
    this.flagVar = { ...res.flag};
    if(this.data.flag.client == null ) {
        this.isSearch = false;
        this.initializeClient();
    }
}

editflag.spec.ts

const testData = {
    "flag":{
        id: null, //string
        description: null,  //string
        url: null,      //string
        client: null
    },
    "action": "edit"
};

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        EditFlagComponent
      ],
      providers: [
        HttpClient,
        HttpHandler,
        {provide: MatDialog, useValue: {} },
        {provide: MatDialogRef, useValue: {} },
        {provide: MAT_DIALOG_DATA, useValue: {testData} },
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(EditFlagComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
  
it('should call flagEdit',() => {
    component.flag.client = testData.flag.client;
    component.flagEdit();
    fixture.detectChanges();
    expect(component.isSearch).tobeFalsy();
});

I also hope that the transition block mentioned below will be covered in the summary:

switch(this.data.action) {
        case 'create':
            this.flagClone = this.initializeFlagClone();
            break;
        case 'edit':
            this.flagEdit();
            break;
        default:
            console.log('No action');
    }

Answer №1

It seems like there is a mistake in your usage of useValue.

Please update this line:

{provide: MAT_DIALOG_DATA, useValue: {testData} },

to the following:

{provide: MAT_DIALOG_DATA, useValue: testData },

Additionally, make sure to remove the line

component.flag.client = testData.flag.client;

from your unit test.

Answer №2

An issue has arisen with the message TypeError: Cannot read property 'client' of undefined. This error occurs at the line this.data.flag.client == null

You have specified

@Inject(MAT_DIALOG_DATA) public data: any,
and in your test, you are using
{provide: MAT_DIALOG_DATA, useValue: {testData} },
This is similar to having {provide: MAT_DIALOG_DATA, useValue: {testData: testData} },` i.e

this.data = { testData: {
    "flag":{
        id: null, //string
        description: null,  //string
        url: null,      //string
        client: null
    },
    "action": "edit"
}}

The issue lies in the fact that you haven't assigned a value to this.data.flag

To rectify this, simply change

{provide: MAT_DIALOG_DATA, useValue: {testData} },
to
{provide: MAT_DIALOG_DATA, useValue: testData },
and then you will be supplying the value correctly

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

Subscription to Observable content failed to run

When a submit button is clicked inside the component HTML, it triggers a function called addCollaborators(). The code for this function can be found below: component.ts emails: string[] = []; constructor(public userService: UserService) {} // Function ...

An issue has arisen regarding the type definition for the random-string module

I am currently working on creating a .d.ts file for random-string. Here is the code I have so far: declare module "random-string" { export function randomString(opts?: Object): string; } When I try to import the module using: import randomString = ...

Show the outcome stored within the const statement in TypeScript

I am trying to display the outcome of this.contract.mint(amount, {value: this.state.tokenPrice.mul(amount)}) after awaiting it. I want to see the result. async mintTokens(amount: number): Promise<void> { try { let showRes = await this.c ...

clicking a table row will activate the *ngFor directive

Incorporating data from an API into a table, I have enabled the functionality for users to click on table rows in order to change the displayed data using background code: <tr [ngClass]="tablerowClass" *ngFor="let dataObject of data$ | async" (click)=" ...

What is the best way to eliminate any extra spaces from a string using typescript?

Currently in my Angular 5 project, I am encountering an issue with using the .trim() function in TypeScript on a string. Despite implementing it as shown below, no whitespace is being removed and also there are no error messages appearing: this.maintabinf ...

Managing Data Types in a React and Express Application

I am working on a project that includes both a React client and a Node-Express backend. Currently, my React app is running with TypeScript and I am looking to switch my backend to TypeScript as well. At the moment, my project structure consists of a clien ...

What is the best method for accessing the properties of a JavaScript object based on input from a textbox?

Just starting out with angular and having trouble generating or updating a table based on text boxes. The schema includes country, sales, and profit fields. There are two text boxes for the x-axis and y-axis inputs. The table should dynamically update when ...

shifting the angular directives to alternate the bootstrap class of hyperlinks

I have a collection of hyperlinks displayed on my webpage. <a href="#" class="list-group-item list-group-item-action active" routerLink='/route1' >Explore First Link</a> <a href="#" class="list-group-item list-group-item-action" r ...

"Using rxjs, a value is delivered within the subscribe function

function createSingleMapService(mapServiceFactory) { return mapServiceFactory.switchSingleMapService().subscribe((service)=>{ return service }) } This snippet is a factory function in Angular that creates a single map service. The 's ...

Combining existing CSS classes with node labels in Cytoscape JS for Angular: A Guide

My project follows a consistent CSS theme, but the node's CSS style doesn't match. I'm looking to adjust the label colors in the CSS based on whether it's day mode or night mode. How can I accomplish this? this.cy = cytoscape({ con ...

Angular 2 - Component remains active upon page transition

I am currently working on a large Angular2 application. I have set up two routes - /rewards which displays a list of all rewards and /reward/{rewardName} which shows detailed information about a specific reward. However, I am facing an issue where each tim ...

Is it advisable to use an if statement or question mark in TypeScript to prevent the possibility of a null value?

Currently delving into TypeScript and exploring new concepts. I encountered a scenario where inputRef.current could potentially be null, so I opted to directly use a question mark which seems to work fine. However, in the tutorial video I watched, they use ...

Angular offers pre-determined values that cannot be altered, known as "

I am currently learning Angular and TypeScript, and I came across a task where I need to create an object or something similar that allows me to define a readable but not editable attribute. In Java, I would have achieved this by doing the following: publ ...

What is the best way to parse JSON data with Typescript?

I am dealing with JSON data structured as follows: jsonList= [ {name:'chennai', code:'maa'} {name:'delhi', code:'del'} .... .... .... {name:'salem', code:'che'} {name:'bengaluru' ...

Events bound to JSX elements created in an array map are not being triggered by React

My current task involves working on a compact react + typescript (1.6) application designed for editing slideshows. The functionality of the app is straightforward. A sidebar on the left displays all existing slides, and upon clicking, a canvas appears on ...

The ngOnChanges lifecycle hook does not trigger when the same value is updated repeatedly

Within my appComponent.ts file, I have a property called: this._userMessage Afterwards, I pass it to the childComponent like so: <child-component [p_sUserMessage]='_userMessage'></child-component> In the childComponent.ts file: @ ...

No element found with the specified exportAs value of "ngForm" on the <form> tag

I am currently experimenting with a template driven form in Angular, but I encountered an error stating **There is no directive with “exportAs” set to “ngForm"** I have made sure to import FormsModule and ReactiveFormsModule in app.module.ts as well ...

"Exploring the Power of Angular Change Detection with Promises in a Hybrid

We are currently in the process of upgrading an AngularJS project to Angular 7 by following the recommended "hybrid" approach where both frameworks coexist. However, we have encountered some issues with change detection when dealing with native promises. T ...

Implement Angular and RxJS functions sequentially

this.functionalityClient.activateFeature(featureName) .pipe( concatMap( feature => { this.feature = feature; return this.functionalityClient.setStatus(this.feature.id, 'activated'); } ), con ...

Experience the power of transforming nested forkjoin operations into observables

Trying to implement a solution in my resolver that involves nested forkjoins and subscribes has been challenging. I attempted using maps, but I still need to fully grasp the concepts of maps/switchMaps/mergeMaps. Even though the code doesn't currently ...