Angular Karma test - Error: Unable to access property 'recipientAddressId' of null

While attempting to test using karma, I encounter the following error...

TypeError: Cannot read property 'recipientAddressId' of null

Here is my Component:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { ApiService } from '../services/api.service';
import { NgxSpinnerService } from "ngx-spinner";

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

  cartId:any;
  recipientDetails:any;
  subscriptionId:any;

  interval;
  timeLeft: number = 20;

  constructor(public router: Router,public apiService: ApiService, private spinner: NgxSpinnerService) { 
    this.spinner.show();
    this.cartId = localStorage.getItem('cartId');

    if(!this.cartId){
      this.router.navigate(['product']);
    }
    this.recipientDetails  = JSON.parse(localStorage.getItem('recipientDetails'));
   
    this.subscriptionDetail();
  }

  subscriptionDetail(){
    this.apiService.subscriptionDetails(this.recipientDetails.recipientAddressId).subscribe((res)=>{
      if(res && res.body && res.body.subscriptionDetails && res.body.subscriptionDetails[0]){
        this.subscriptionId = res.body.subscriptionDetails[0].subscriptionId;
        this.spinner.hide();
      } else {
        setTimeout(()=>{ 
          this.subscriptionDetail();
        }, 2000);
      }
      
     });
  }


  ngOnInit(): void {
    localStorage.removeItem('zipCode');
    localStorage.removeItem('recipientDetails');
   
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.router.navigate(['home']);
        console.log("Payment Success.");
        clearInterval(this.interval);
      }
    },1000)


  }


}

Spec.ts

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

import { ConfirmationComponent } from './confirmation.component';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClient, HttpClientModule, HttpHandler } from '@angular/common/http';
import { FormBuilder } from '@angular/forms';
import { TestAlertService } from '../services/test-alert.service';
import { AlertService } from 'ngx-alerts';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ConfirmationComponent ],
      imports: [RouterTestingModule,HttpClientModule],
      providers: [HttpClient,FormBuilder,HttpHandler,{ provide: AlertService, useClass: TestAlertService }]
    })
    .compileComponents();
  }));

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

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

Thank you for your attention..................................................................................................................................................................................................................................................

Answer №1

Make sure to check for the presence of recipientDetails in local storage when running your tests. Consider updating the constructor to include default values if it is not found.

this.recipientDetails = JSON.parse(localStorage.getItem('recipientDetails')) || {};

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

Exploring the world of Typescript class decorators and accessing its content from within

Greetings, I am searching for a method to define a class in TypeScript and retrieve its value from within the parent. abstract class Base{ fetchCollectionName(): string{ // code here to return child class attribute value } } @Collectio ...

Issue Encountered during 'ng build --prod' Command: Prompt requesting addition of '@Pipe/@Directive/@Component annotation'

Encountered an error while running ng build --prod on my MEAN Stack App. The error message reads : ERROR in : Unexpected module 'FlashMessageModule in C:/mean/angular/node_modules/angular-flash-message/dist/flash-message.module.d.ts' declared ...

Unauthorized Access: Azure Web App and Typescript - "Access to this directory or page is restricted."

After developing a NodeJS server in Typescript, I attempted to deploy it to an Azure Web App through VS19. While the project functions correctly internally, when published to Azure, I encountered permission issues. The project was built using the "Basic A ...

Utilizing Angular 2 to Make Restful API Requests with Windows Authentication

I am currently facing an issue with my .net web api hosted on IIS 7, which uses windows authentication. My goal is to access this web api using Angular 2, TypeScript, and Node.js. Initially, I encountered an error stating 'Response to preflight reques ...

Exploring the functionalities of React Native with react-hook-form and implementing them with TypeScript

I've been working on creating a custom Input component in react native using typescript for the react-hook-form library. type CustomInputProps = { name: any, control: any } const CustomInput: FC<CustomInputProps> = ({name, control, ...p ...

Steps for creating an Observable<Object[]> using data from 2 different API requests

My goal is to retrieve an Observable<MyResult[]> by making 2 separate API calls to load the necessary data. The first call is to load MyItem. The second call is to load Gizmos[] for each item. In a previous question, I loaded the second API into t ...

Change the scrolling speed while dragging in Angular CDK Drag and Drop

UPDATE 11.07.2020 There is an ongoing issue on Github related to this topic, you can find more information here: https://github.com/angular/components/issues/19401 ORIGINAL POST I am looking for a way to customize the scrolling speed while dragging an i ...

Leveraging es6-promise in conjunction with TypeScript 2.1 and ES5 Webpack for streamlined async/await functionality

Utilizing es6-promise with TypeScript version 2.1.1 that targets ES5 and webpack in my project has presented some challenges. app.ts import "es6-promise/auto"; export class Foo { bar() : Promise<string>{ return Promise.resolve("baz"); ...

Tips on expanding an interface of a subclass

Using the latest versions of TypeScript and ReactJS together has presented a challenge when it comes to extending classes and their interfaces. To address this issue for several form elements that share common validation methods, I have created a BaseComp ...

Interpolation within ngStyle allows dynamic styling to be applied in

When creating a column component for use within a grid in Angular, I am struggling with implementing a media query using ngStyle. Here is what my code looks like so far: import { Component, Input } from '@angular/core' const smMin = '48em& ...

Expanding an abstract class with Typescript

In order to create a new instance of a base abstract class that implements an interface, I have the interface, the base class, and some properties in an Angular component. Surprisingly, no errors are thrown in the browser (perhaps due to JavaScript's ...

Deconstructing Angular 2 Custom Pipes

As I delve deeper into learning Angular 2, my recent endeavor involves creating a custom pipe to filter results in my gallery by category. Unfortunately, the resources I've been referring to lack detailed explanations on how custom pipes actually work ...

MatFormFieldControl with custom styling is failing to display the initial value in the view

Take a look at the stackblitz example here: https://stackblitz.com/edit/angular-material-components-demo-5k6gey?file=src/app/app.component.html An issue arises when there is an initial value present in the view, as it is not displayed properly. Additional ...

Implementing ng-multiselect-dropdown with option grouping

I've been working on organizing my options in ng-multiselect-dropdown but I'm having trouble finding references on how to do it. Here's the code I have so far: .html <ng-multiselect-dropdown [placeholder]="'Select one'" [data]= ...

Leveraging Angular Firebase MatTable with the power of 2 observables in 1

I'm currently facing an issue with my Firebase database data structure where I have a reference to a user id. Here's an example of the original data in my collection: { city: new york, country: usa addedBy: feibf78UYV3e43 // This is the USER ID ...

What is the best method for filling out the form fields with the data that has been chosen

I am working with a database where I need to be able to add, edit, and delete records. Adding records works perfectly fine. However, when I select a row from the displayed data, I want the form fields to be automatically filled so that the user can easil ...

Cast the variable to access nested data

I'm currently working with data retrieved from an API call in the form of nested objects. My goal is to extract and organize this information for display in a table. In my code, I am using a loop with for (const [key, value] of Object.entries(result)) ...

What is causing the transpiler to not be triggered by the code change?

My current project involves using a TypeScript backend for a Dialogflow application with fulfillment. I initially used a preconfigured project template and didn't delve into the details. I work in VS Code and never explicitly build my code. Instead, ...

How to dynamically add a component in Angular 7/8 when a button is clicked

I am facing an issue with importing a common component when a button is clicked. The component contains standard HTML elements which can be viewed on Stackblitz However, upon clicking the button, an error is thrown: Error: Cannot read property 'c ...

Connecting JavaScript files in angular 4: A step-by-step guide

Currently, I am utilizing Angular 4 and looking to have my JavaScript file work globally. Here is how I have declared it in the index.html file: <script src="assets/js/jquery-1.11.1.min.js"></script> <script src="assets/js/bootstrap.min.js"& ...