The Karma tool is throwing a TypeError because it is unable to access the 'length' property of a null value

Despite reviewing numerous inquiries regarding this error, none have provided insight into identifying the root cause of the issue. How can I pinpoint the origin of this error and what steps can I take to resolve it?

TypeError: Cannot read property 'length' of null
at HttpHeaders.applyUpdate (webpack:///./node_modules/@angular/common/fesm5/http.js?:235:27)
at eval (webpack:///./node_modules/@angular/common/fesm5/http.js?:206:74)
at Array.forEach (<anonymous>)
at HttpHeaders.init (webpack:///./node_modules/@angular/common/fesm5/http.js?:206:33)
at HttpHeaders.forEach (webpack:///./node_modules/@angular/common/fesm5/http.js?:271:14)
at Observable.eval [as _subscribe] (webpack:///./node_modules/@angular/common/fesm5/http.js?:1481:25)
at Observable._trySubscribe (webpack:///./node_modules/rxjs/_esm5/internal/Observable.js?:48:25)
at Observable.subscribe (webpack:///./node_modules/rxjs/_esm5/internal/Observable.js?:34:22)
at eval (webpack:///./node_modules/rxjs/_esm5/internal/util/subscribeTo.js?:33:31)
at subscribeToResult (webpack:///./node_modules/rxjs/_esm5/internal/util/subscribeToResult.js?:10:84)
at ____________________Elapsed_26_ms__At__Tue_Sep_04_2018_11_58_19_GMT_0200__hora_de_verano_de_Europa_central_ (http://localhost)
at Object.onScheduleTask (webpack:///./node_modules/zone.js/dist/zone-testing.js?:107:22)
at ZoneDelegate.scheduleTask (webpack:///./node_modules/zone.js/dist/zone.js?:400:51)
at Object.onScheduleTask (webpack:///./node_modules/zone.js/dist/zone.js?:296:29)
at ZoneDelegate.scheduleTask (webpack:///./node_modules/zone.js/dist/zone.js?:400:51)
at Zone.scheduleTask (webpack:///./node_modules/zone.js/dist/zone.js?:231:43)
at Zone.scheduleMacroTask (webpack:///./node_modules/zone.js/dist/zone.js?:254:25)
at scheduleMacroTaskWithCurrentZone (webpack:///./node_modules/zone.js/dist/zone.js?:1113:25)
at eval (webpack:///./node_modules/zone.js/dist/zone.js?:2089:28)

The error is observable in both the Chrome browser console and during test execution with Karma.

Another unsuccessful test message exhibits the following:

[object ErrorEvent] thrown

I am unsure how to troubleshoot this bug as well.

UPDATE: A simplified, comprehensive, and reproducible sample

Service:

import { HttpClient } from '@angular/common/http';
import { Country } from '../countries/country.model';
import { Observable } from 'rxjs';
import { Configuration } from '../../constants';

@Injectable({
    providedIn: 'root'
})
export class DropdownService {

    private server: String;

    constructor(
        private http: HttpClient,
        private configuration: Configuration
    ) {
        this.server = this.configuration.serverOCD;
    }

    getCountries(): Observable<Country[]> {
        return this.http.get<Country[]>(this.server + '/api/v1/country');
    }
}

Component:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl } from '@angular/forms';

import { DropdownService } from '../services/dropdown.service';
import { Country } from './country.model';
import { Observable } from 'rxjs';

@Component({
    selector: 'dropdown-countries',
    templateUrl: './countries.component.html',
    styleUrls: ['./countries.component.css']
})

export class CountriesComponent implements OnInit {

    countries$: Observable<Country[]>;
    countries: Country[] = [];
    countriesForm: FormGroup;
    country: FormControl;

    constructor(
        private fb: FormBuilder,
        private dropdownService: DropdownService,
    ) { }

    ngOnInit() {
        this.countriesForm = this.fb.group({
            country: this.fb.control(new Country().code = '')
        });

        // Attempt 1
        this.getCountries();

        // Attempt 2
        this.countries$ = this.dropdownService.getCountries();
    }

    getCountries() {
        this.dropdownService.getCountries().subscribe(
            data => this.countries = data,
            err => console.error(err),
            () => console.log('done loading countries')
        );
    }

}

Template:

<div [formGroup]="countriesForm">
    <select id="countriesDropdown" class="form-control form-control-sm" formControlName="country">
        <option value="" disabled>Choose a Country</option>
        <option *ngFor="let country of countries$ | async" [ngValue]="country">{{country.longDescription}}</option>
    </select>
</div>
<p>Form value: {{ countriesForm.value | json }}</p>

Answer №1

After extensive 48-hour research, I finally identified the issue stemming from a piece of code that caught me by surprise:

GenericService:

@Injectable()
export class JWTInterceptor implements HttpInterceptor {

    private token: string;

    constructor(
        private config: Configuration,
        private authStore: AuthenticationStore
    ) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        this.token = this.authStore.getToken();

        if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

        req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
        req = req.clone({ headers: req.headers.set('Authorization', this.token) });

        return next.handle(req);
    }
}

SharedModule:

providers: [
    GenericService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: JWTInterceptor,
      multi: true,
    }
],

Despite all requests being intercepted by JWTInterceptor, causing unintended errors, I managed to circumvent this by utilizing HttpBackend to exclude that interceptor:

DropdownService:

constructor(
    private http: HttpClient,
    private handler: HttpBackend, // to ignore interceptor
    private configuration: Configuration
) {
    this.http = new HttpClient(this.handler); // implement in HttpClient
    this.server = this.configuration.serverOCD;
}

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

Angular - Utilizing NgRx selector for efficient data update notifications

Is there a method to create a "data updated" indicator when I am not interested in the actual updated data itself? Consider a scenario with a reducer: const initialState: SomeReducer = { dataInQuestion: Array<SomeDto>, ... } Following an action ...

Displaying a TypeScript-enabled antd tree component in a React application does not show any information

I attempted to convert the Tree example from antd to utilize TypeScript, however, the child-render function does not seem to return anything. The commented row renders when I remove the comment. The RenderTreeNodes function is executed for each element in ...

Unable to bind to property as it is not recognized as a valid attribute of the selector component

I have a situation where I need to pass a variable from one component to another using @input. Here is my parent component : @Component({ selector: 'aze', templateUrl: './aze.component.html', styleUrls: [('./aze.compo ...

Using TypeScript arrow functions to define parameters

When setting "noImplicitAny": true in TypeScript, you may encounter the following errors: Parameter 'x' implicitly has an 'any' type This error can occur with the code snippet: .do(x => console.log(x)); Another error you might s ...

Stopping Angular2 HTTP Requests - A Guide to Aborting or Cancelling Executing Requests

Currently, I am implementing an autocomplete feature for my search functionality. handleKeypress(searchValue){ // Code to make an AJAX request with the search value // .... } I am looking to cancel any previous HTTP requests each time a keypress ev ...

Attempting to access jQuery from an external JavaScript file within the Ionic 5 framework

Currently, I am working on an Ionic app with Angular. I want to call my JavaScript function when the document is ready in the JS file, but I keep encountering an error. Here is my watch.page.html: <ion-content> <div class="videoContainer&qu ...

Leveraging Angular modules within web workers

Currently, I am attempting to leverage the Angular 8 JIT compiler within a WEB WORKER. Unfortunately, when trying to import the Compiler module or any other Angular module in the web-worker.ts file, I encounter an error. /// <reference lib="webworker ...

Obtaining data objects with Angular 2 from JSON

Recently, I received a URL that includes data arrays in JSON format. My goal is to retrieve and utilize all elements within it: However, when attempting this, I end up with everything but nothing specific. For instance: How can I access data.name or data. ...

The source code in VS Code was not accurately linked

I'm currently facing an issue with running my angular2 project from vs code. Below are the contents of my tsconfig and launch.json files. tsconfig.json { "compilerOptions": { "declaration": false, "emitDecoratorMetadata": true, "experi ...

Creating dynamic elements in Angular2 componentsIn Angular2, you can seamlessly

Utilizing the Google Maps JavaScript API in my project, I faced the challenge of displaying an Angular component within an InfoWindow. After loading the Google Maps API with the Jsonp service, I had access to the google.maps.Map object. In a component, I ...

Is it possible to set a form control value as an object and display its label within an input field?

I am working on a basic form that includes an input field with autocomplete using Angular Material components. The issue I am facing is that when I select a value from the autocomplete box, the input field displays [Object object] as the value instead of t ...

Sending data from an Angular 2 application to a Spring MVC Rest API using HTTP POST method

I'm encountering an issue while attempting to perform an angular 2 http post JSON with multiple attributes to Spring MVC using @RequestParam. Despite my efforts of searching for a solution, I have not been successful in binding it to my object. I even ...

Combine and transform multiple hierarchical JSONs into a new format

I'm facing a challenge where I need to merge two JSON objects and convert them into a different format using TypeScript in a React project. Initially, I tried implementing this with a recursive function as well as a reducer, but unfortunately, it didn ...

Array of generic types in Typescript

Here's a method that I have: getFiveObjectsFromArray(array: T[]) { return array.slice(0, 5); } I've been using this method multiple times. Is there a way in TypeScript to pass a generic argument instead of using multiple types? Also, when ...

Dynamically inserting Angular 2 components at specific or nth positions

Having trouble adding components at specific index? Check out the Plunker example linked below: PlunkerAddRemoveComponents In the provided code snippet, components can only be added at a specific index the first time. export class AddRemoveDynamic { ...

Do we need to import Vue in every component when using Nuxt with TypeScript?

I recently integrated TypeScript into Nuxt using the guidelines provided in the documentation: However, I have a specific question regarding component setup. Should I always include import vue from "vue" and export default Vue.extend ({}); in al ...

There are a pair of Ionic2 menus; one is currently visible while the other remains hidden

I am having an issue with my Ionic2 app where I have two pages, each with similar menus named XXX.html. One page displays its menu correctly, but the other does not show its menu at all. Is there a limitation in Ionic2 that prevents having two menus on the ...

Creating nested Array objects in a table format in Angular 2 without using a nested table and ensuring that columns remain aligned

I'm currently working on generating a table with nested Array objects. Unfortunately, using nested tables is causing alignment issues between the header of the outer table and the columns in the inner table. Here's an example of the classes I&ap ...

Content from PHP's unlink() function continues to persistently display

I run an Angular front end along with a PHP back end for my website. I utilize PHP's unlink function to remove specific images from Angular's assets folder: $fileToDelete = "../src/assets/images/".$name; unlink($fileToDelete) or die("Error delet ...

The assigned type 'string' for Apache ECharts does not match the expected type 'pictorialBar'

This demonstration is functional. Nevertheless, the options utilize any and my goal is to convert them to the EChartOption type. This is my current progress and the demonstration compiles successfully with this setup (With type: 'bar' commented ...