Karma Unit test: Issue with accessing the 'length' property of an undefined value has been encountered

While running karma unit tests, I encountered a similar issue and here is what I found:

One of my unit tests was writing data to a json file, resulting in the following error:

ERROR in TypeError: Cannot read property 'length' of undefined
    at createSourceFile (...\node_modules\typescript\lib\typescript.js:15460:109)
    at parseSourceFileWorker (...\node_modules\typescript\lib\typescript.js:15389:26)
    at Object.parseSourceFile (...\node_modules\typescript\lib\typescript.js:15338:26)
    at Object.createSourceFile (...\node_modules\typescript\lib\typescript.js:15192:29)
    at new TypeScriptFileRefactor (...\node_modules\@ngtools\webpack\src\refactor.js:79:35)
    at Object.findLazyRoutes (...\node_modules\@ngtools\webpack\src\lazy_routes.js:18:22)
    at AotPlugin._findLazyRoutesInAst (...\node_modules\@ngtools\webpack\src\plugin.js:220:50)
    at _donePromise.Promise.resolve.then.then.then.then.then (...\node_modules\@ngtools\webpack\src\plugin.js:499:24)
    at process._tickCallback (internal/process/next_tick.js:109:7)

To troubleshoot, I added console.log statements in createSourceFile() and AotPlugin._findLazyRoutesInAst.

Upon closer inspection of AotPlugin._findLazyRoutesInAst, I noticed the loop structure:

for (const filePath of changedFilePaths) { }
. Printing out 'changedFilePaths', I observed the following:

These are changedFilePaths ==>
[ '.../src/polyfills.ts',
'.../src' <--- Please note the missing file name.
]

This realization led me to understand the source of the error.

The problem persisted whenever changes were made to any files, not just .ts files. Even modifying a json file produced the same error.

I attempted to address the issue by making adjustments in karma.conf.js (following official config documentation):

exclude: ["./src/nonCodeRelatedData/**"]
.
and

files: [ {pattern: "./src/nonCodeRelatedData/**", watched: false, included: false, served: false}]

However, these changes did not resolve the problem.

If someone could provide guidance on how to fix this issue, it would be greatly appreciated.

Answer №1

I encountered a similar issue while using angular 4 and angular-cli versions 1.6.8 - 1.7.3... My temporary solution involved modifying a file in the node_modules directory, as detailed in this link or potentially upgrading to angular 5 (although I have not personally tested this).

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

"Unlock the secret to effortlessly redirecting users to a designated page when they click the browser's back

So I'm facing the challenge of disabling the browser back button on multiple routes and sending requests to the backend is resulting in inconsistent behavior. I don't want to create a multitude of similar API requests each time. Currently, I have ...

Identify the CSS class for the ionic component on the webpage

Currently, I am in the process of developing an application using ionic 2 and angular 2. Within this app, I am utilizing the ionic 2 component known as ModalController. Unfortunately, I have encountered a challenge when attempting to adjust the size of th ...

I need guidance on retrieving items from the useRouter() hook when utilizing Next.js with the App Router approach

This code snippet demonstrates how to use Pages Router in React import { useRouter } from "next/router"; import React from "react"; function ShowroomListings({}) { const router = useRouter(); const { listingId } = router.query as ...

Using a custom TemplateRef in NgxDatatable

In the project I am currently working on, the tables have a specific wrapper around them. To prevent repetition of code, I am seeking a method to create a template where each component passes an ng-template that will be rendered within the custom table tem ...

When the page hosted on Vercel is reloaded, `getStaticProps` does not function as expected

I'm currently working on a nextjs project and running into an issue where one of the pages returns a 404 error when it's reloaded. Within the page directory, I am using getStaticProps. pages - blogs.tsx - blog/[slug].tsx - index.tsx ...

What is the best way to distinguish shared services from other services in Angular 6 and above?

There was a time when I frequently heard the term "shared services" in relation to sharing data between unrelated components in Angular. However, I started questioning whether every service is actually classified as a shared service or not. If it is cons ...

Propagating numerical values through iterative iterations

I am currently facing an issue with passing values as props to a component using the forEach method in JavaScript. In addition to passing the existing values from an array, I also want to send another value that needs to be incremented by 1 for each iterat ...

What's the Advantage of Using a Getter for a Public Field in Angular?

Having come from a background in Java where the practice is to make variables as private as possible, I've noticed in Angular that private fields are not used frequently. What is the reasoning behind not making fields private if it's possible? ...

Awaiting server token before executing HttpInterceptor in Angular 2+

I understand that a similar question may have been asked before, but after going through all the available resources, I am still unable to find a solution to my problem. My issue lies in the fact that HttpIntercept.intercept needs to return next.handle(re ...

Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test. The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org ...

LocalStorage in Angular application failing to function in Android web view

Working with Angular 4, I've developed a web application that stores the user security token in localStorage after login. The application uses this localStorage value to control the visibility of certain links, such as hiding the login button once th ...

What is the best way to iterate through an array within a class in Angular 2?

I am trying to iterate over an array named data, within another array containing 'champions'. Can anyone provide the correct syntax for this? I can successfully loop through all the champions within my IChampion interface, but I'm having tro ...

Creating a generic type in TypeScript that represents a union of keys from type T's properties

Is there a way to determine the result type (TTarget) based on TSource and the provided property names (keyof TSource)? I have this function that copies specified properties to a new object: export declare type PropertyNamesOnly<T> = { [K in keyof ...

Tips for incorporating ACE Editor syntax highlighting rules into an Angular application

I am attempting to create custom highlighter rules by referencing examples from here and here. import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import * as ace from 'ace-builds'; import 'ace-builds/src- ...

Issues arise when attempting to override attributes within the HTML of a parent component in Angular

Why does overriding an attribute in a child class that extends from another not work as expected? Here's a made-up scenario to simplify the issue: Parent class file: gridbase.component.ts import { Component, OnInit } from '@angular/core'; ...

How to delete an item from an object in TypeScript

Can you help with filtering an object in Angular or TypeScript to eliminate objects with empty values, such as removing objects where annualRent === null? Additionally, what method can we use to round a number like 2.833333333333335 to 2.83 and remove the ...

What is the best approach to dealing with a non-TypeScript project that is requesting the installation of @types for

With the project set up using create-react-app and custom-react-scripts to utilize decorators for MobX, I am aiming to incorporate the react-c3js library for data visualization. Surprisingly, everything is functioning correctly, but there's a warning ...

Creating custom generic functions such as IsAny and IsUnknown that are based on a table of type assignability to determine

I attempted to craft a generic called IsAny based on this resource. The IsAny generic appears to be functioning correctly. However, when I implement it within another generic (IsUnknown), it fails: const testIsUnknown2: IsUnknown<any> = true; // iss ...

Setting up a passthrough for a directory of external resources in Angular

Issue: I am currently facing a challenge with a project that requires accessing photos from a system that has recently been updated from AngularJs to Angular 16. Initially, we were able to serve these photos from a virtual directory like https://myawesom ...

Creating adaptable Object Properties using Zod

Just dipping my toes into Typescript, Zod, and Trpc. Let's say I have a schema for animals and plants. I want to keep all their shared properties in the main part of the schema, while putting more specific details into a sub-object named custom. (jus ...