Encountering an Angular 10 error: Trying to access a property that is undefined during test

In my journey to master Angular, I have taken on the challenge of building a clone of a todo-list application.
Here are the interfaces and components that I have defined for this project:

ListItem:

import { Step } from './step';

export interface ListItem {
    id: number;
    description: string;
    done: boolean;
    steps: Step[];
}

Step:

export interface Step {
    description: string,
    done: boolean
}

step.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { ListItem } from '../listitem';
import { Step } from '../step';
import { StepService } from '../step.service';

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

  @Input() listItem: ListItem;

  constructor(private stepService: StepService) { }

  ngOnInit(): void {
  }

  onSetStepDone(step: Step): void {
    this.stepService.setStepDone(step);
  }
}

step.component.html

<div class="section-item">
    <span class="title">Steps</span>
    <ul class="steps">
        <li *ngFor="let step of listItem.steps">
            <div class="steps-body">
                <div *ngIf="step.done === true; else stepNotDone">
                    <div (click)="onSetStepDone(step)">
                        <span data-is-focusable="true" class="checkBox-sm completed big" role="checkbox" aria-checked="true" tabindex="0">
                            <i class="icon svgIcon ms-Icon checkbox-completed-20">
                                <svg focusable="false" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                                    <path fill-rule="evenodd" d="M10.9854 15.0752l-3.546-3.58 1.066-1.056 2.486 2.509 4.509-4.509 1.06 1.061-5.575 5.575zm1.015-12.075c-4.963 0-9 4.037-9 9s4.037 9 9 9 9-4.037 9-9-4.037-9-9-9z"></path>
                                </svg>
                            </i>
                        </span>
                    </div>
                </div>

                <button tabindex="0" class="steps-titleWrapper">
                    <span class="listItem-title" [class.done]="listItem.done == true">
                        {{step.description}}  
                    </span>
                </button>
            </div>        
        </li>
    </ul>
            
</div>

<ng-template #stepNotDone>
    <div (click)="onSetStepDone(step)">
        <span data-is-focusable="true" class="checkBox-sm big" role="checkbox" aria-checked="false" tabindex="0">
            <i class="icon">
                <svg focusable="false" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                    <path fill-rule="evenodd" d="M12 20c-4.411 0-8-3.589-8-8s3.589-8 8-8 8 3.589 8 8-3.589 8-8 8m0-17c-4.963 0-9 4.037-9 9s4.037 9 9 9 9-4.037 9-9-4.037-9-9-9"></path>
                </svg>
            </i>
            <i class="icon checkBox-sm-hover">
                <svg focusable="false" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                    <g fill-rule="evenodd">
                        <path d="M12 20c-4.411 0-8-3.589-8-8s3.589-8 8-8 8 3.589 8 8-3.589 8-8 8m0-17c-4.963 0-9 4.037-9 9s4.037 9 9 9 9-4.037 9-9-4.037-9-9-9"></path>
                        <path d="M10.9902 13.3027l-2.487-2.51-.71.704 3.193 3.224 5.221-5.221-.707-.707z"></path>
                    </g>
                </svg>
            </i>
        </span>
    </div>
</ng-template>

Every time I attempt to run a test on step.component.spec.ts, an error is thrown indicating that the property "steps" cannot be read.

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

import { StepComponent } from './step.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ StepComponent ]
    })
    .compileComponents();
  }));

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

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

It seems like the line

<li *ngFor="let step of listItem.steps">
might be causing the failure in the test but I am unable to identify the issue... did I make a mistake somewhere?

Any help would be greatly appreciated!

Answer №1

Ensure to properly initialize the listItem variable within your test scenario. Typically, this value is passed from the parent component in a real-world application. However, since the focus of the test is on your StepComponent, there may be instances where no value is provided using the @Input (resulting in an undefined state).

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

Bundling JSPM with an external system JS file

Currently, I am loading my Angular2 file as a System js module from a CDN. Within my project, I have multiple files importing various System js modules of Angular2. However, I am now looking to bundle my local JavaScript files using JSPM. But when I ente ...

How to add a service to a static function in Angular

After incorporating a logger service into my project, I have encountered an issue with using it in NGXS static selectors. The selectors in NGXS are static methods, which prevent me from accessing the logger service injected via Angular DI. Are there any e ...

When transitioning to generics, the narrowing of types in TypeScript is sometimes lost

I am intrigued by this scenario where Test1 fails while Test2 succeeds. I wonder if there is a way to have Test1 pass without altering the generic signature: enum TableType { Shipment = "Shipment", Batch = "Batch", } type Test& ...

Typescript: parameter must be included if another is also required

In the user interface, the parameter c is mandatory only if the parameter a is set to true. interface IArguments { a: boolean, b: string, c: string } The solution below seems to be effective, but how can I exclude the c parameter in the first scenar ...

The post method is functioning properly in browsers such as Firefox, Internet Explorer, and Chrome; however, it is not working in the Edge browser

I am encountering an issue with a post method in the Edge browser. Even though I am able to receive responses for the same request in other browsers like Internet Explorer, Chrome, and Firefox, Edge seems to be not responding at all. Despite conducting a s ...

Issue encountered while executing the "npm run server" directive

The dot '.' is giving an error, saying it is not recognized as an internal or external command, operable program, or batch file. https://i.sstatic.net/CM6OL.png ...

Using Angular to create a single component instance that can be displayed multiple times within the same application hierarchy through modal

I have a scenario where there is an application with componentA (with selector 'dyn-form') responsible for generating a dynamic form. I utilized this to create the form page... On this form page, when a button is clicked, a dynamic component is l ...

Switching the scope or zone in Angular when handling events external to Angular

Currently, I am utilizing an external library within my Angular 6 application that incorporates customizable event listeners. Specifically, I am employing flowchart.js, although similar issues may arise with other libraries. In the case of flowchart.js, i ...

Issue with Radio Button Value Submission in Angular 6 and Laravel 5.5

I developed a CRUD application utilizing Angular and Laravel 5.5. Within this application, I included three radio buttons, but encountered an error when trying to retrieve their values... A type error occurred indicating it was unable to read the data t ...

Stop repeated form submissions in Angular using exhaust map

How can we best utilize exhaust Matp to prevent multiple submissions, particularly when a user is spamming the SAVE button? In the example provided in the code snippet below, how do we ensure that only one submission occurs at a time even if the user click ...

Ways to employ a Hyphen(-) to connect two strings within an ngIf condition in Angular 9

I'm dealing with an IF condition in HTML that checks for permission to access a specific page: *ngIf="permission?.product-report?.list_product_report" The name "product-report" is static and directly used in the condition. However, whe ...

Authenticating Keycloak Object in Angular 2 - Verify the Authenticated Status

Incorporating the Keycloak authentication service into my Angular 2 project has been a learning experience. I have set up a service to handle logging in and out functionalities. Successfully authenticating a user and logging them out was relatively smooth ...

Can I include `ChangeDetectorRef` in an Angular 4 service constructor?

In my service file, I have a system that alerts about Subjects. The value is set and then reset to null after 3 seconds using the setTimeout() method. However, upon adding changeDetection: ChangeDetectionStrategy.OnPush to the app.component.ts, it appears ...

Angular drag and drop feature for interacting with intersecting elements like rows and columns within a table

I am currently working on implementing two intersecting drag and drop functionalities using cdkDragDrop. Although I generally try to avoid using tables, I have created one in this case for the sake of easier explanation. Here is the link to StackBlitz: ht ...

Issue with directive implementation of regex test as attribute - validations in typescript and angular

I am currently working on a project to create a module with custom validation directives. These validations are implemented using regular expressions (regex). The specific error I encountered is: Error: [$injector:unpr] Unknown provider: REG_EXPProvid ...

What is the process for translating the aria-label to "Open calendar" in a different language for the angular md-datepicker icon?

Check out my latest demo on using the angular md-datepicker Looking to customize or translate the aria-label text for the icon in the angular md-datepicker, as shown in the image below. ...

The GET Request made for an Image in an Angular Component results in a 404 error message indicating

I have been working on uploading and fetching images from my mongodb database. Utilizing multer for the image uploads, along with express and mongoose for handling GET/POST requests has been successful so far. The process involves uploading the image to th ...

How can I retrieve the `checked` state of an input in Vue 3 using Typescript?

In my current project, I am using the latest version of Vue (Vue 3) and TypeScript 4.4. I am facing an issue where I need to retrieve the value of a checkbox without resorting to (event.target as any).checked. Are there any alternative methods in Vue tha ...

Having trouble with Heroku deployment? Unsure of the correct way to deploy your Angular App + NodeJs?

Here's a recent log using heroku logs --tail I'm facing some issues and not sure what's wrong :( 2019-07-23T14:46:07.163085+00:00 app[api]: Release v1 created by user ************************* 2019-07-23T14:46:07.163085+00:00 app[api]: Ini ...

Using the amDateFormat pipe in Ionic 3's Lazy Loading feature

Currently, I am using Ionic3 and working on transitioning to Lazy Loading to enhance the startup performance. Since converting my ChatsPage to lazy loading, I have encountered an issue with pipes. The error message points to a specific line in my chats.ht ...