There was an issue thrown during the afterAll function: Unable to access properties of undefined

Recently, I upgraded my Angular project from version 15 to 15.1 and encountered an error while running tests. To replicate the issue, I created a new Angular 15.1 project using the CLI and generated a service with similar semantics to the one causing problems in my project.

Service

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class StorageServiceService {
  public static readonly A = 'a';
  public static readonly B = StorageServiceService.A + 'b';
  public static readonly C = StorageServiceService.A + 'c';

  constructor() { }
}

Test

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

import { StorageServiceService } from './storage-service.service';

describe('StorageServiceService', () => {
  let service: StorageServiceService;

  beforeEach(() => {
    TestBed.configureTestingModule({});
    service = TestBed.inject(StorageServiceService);
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('test', () => {
    expect(StorageServiceService.A).toEqual('a')
    expect(StorageServiceService.B).toEqual('ab')
    expect(StorageServiceService.C).toEqual('ac')
  })
});

Running the tests resulted in the following error:

Chrome 109.0.0.0 (Mac OS 10.15.7) ERROR
  An error was thrown in afterAll
  Uncaught TypeError: Cannot read properties of undefined (reading 'A')
  TypeError: Cannot read properties of undefined (reading 'A')
      at Object.2494 (http://localhost:9877/_karma_webpack_/webpack:/src/app/storage-service.service.ts:8:52)
      at __webpack_require__ (http://localhost:9877/_karma_webpack_/webpack:/webpack/bootstrap:19:1)
      at Object.283 (http://localhost:9877/_karma_webpack_/main.js:86:82)
      at __webpack_require__ (http://localhost:9877/_karma_webpack_/webpack:/webpack/bootstrap:19:1)
      at __webpack_exec__ (http://localhost:9877/_karma_webpack_/main.js:186:48)
      at http://localhost:9877/_karma_webpack_/main.js:187:126
      at Function.__webpack_require__.O (http://localhost:9877/_karma_webpack_/webpack:/webpack/runtime/chunk loaded:23:1)
      at http://localhost:9877/_karma_webpack_/main.js:188:56
      at webpackJsonpCallback (http://localhost:9877/_karma_webpack_/webpack:/webpack/runtime/jsonp chunk loading:34:1)

I am currently using Node 18.12.1 with npm 9.2.0.

package.json

{
  "name": "test-app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^15.1.0",
    "@angular/common": "^15.1.0",
    "@angular/compiler": "^15.1.0",
    "@angular/core": "^15.1.0",
    "@angular/forms": "^15.1.0",
    "@angular/platform-browser": "^15.1.0",
    "@angular/platform-browser-dynamic": "^15.1.0",
    "@angular/router": "^15.1.0",
    "rxjs": "~7.8.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.12.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.1.1",
    "@angular/cli": "~15.1.1",
    "@angular/compiler-cli": "^15.1.0",
    "@types/jasmine": "~4.3.0",
    "jasmine-core": "~4.5.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "typescript": "~4.9.4"
  }
}

Reverting back to Angular 15 resolved the issue. The upgrade process was done using the angular CLI automatically.

Answer №1

Is this the correct format for your test code?

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

import { StorageServiceService } from './storage-service.service';

describe('StorageServiceService', () => {
    let service: StorageServiceService;
    
    beforeEach(() => {
        TestBed.configureTestingModule({});
        service = TestBed.inject(StorageServiceService);
    });
    
    it('should be created', () => {
        expect(service).toBeTruthy();
    });
    
    it('test', () => {
        expect(service.A).toEqual('a')
        expect(service.B).toEqual('ab')
        expect(service.C).toEqual('ac')
    })
});

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 - Brilliant time selection tool (BTS) The TimePicker feature fails to automatically switch to selecting minutes after choosing the hour

I'm currently implementing the Amazing time picker in my app and I'm facing an issue where it doesn't automatically switch to minutes after selecting the hour. component.html <input type="time" atp-time-picker formControlName="time" cla ...

What strategies can we use to minimize the number of times a service needs to be called when instantiating a recursive component that relies on it?

Check out this example of a component featuring the use of FormService in its providers: @Component({ selector: "app-block", templateUrl: "./block.component.html", styles: ['.block_children { padding-left: 50px;}'], providers: [FormServi ...

What are the steps to generate an npm package along with definition files?

Is it possible to create an NPM package with definition files containing only interfaces declared in *.ts files? Consider a scenario where we have two interfaces and one class definition: export interface A { id: number; } export interface B { name: s ...

Encountered an issue with running tests in vscode-test - runTests function throwing

Setting up tests for my vscode extension for the first time and encountering an issue. I copied and pasted the example from code.visualstudio's /working-with-extensions/testing-extension. However, I'm facing an error when trying to call runTest ...

The bidirectional data binding between two components is only functioning for the initial letter

Encountering a peculiar error that I have been researching with no luck in finding a solution. Most of the related findings are outdated and ineffective. Error Message An error is triggered when two-way binding to a property: 'Expression has chang ...

Angular 2 issue with nested form elements

Looking to build a form that includes nested sub/child components within it. Referring to this tutorial: https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2 https://plnkr.co/edit/clTbNP7MHBbBbrUp20vr?p=info List of modificatio ...

Step-by-step guide on resolving the error message "Unable to identify the dependencies of task ':app:preDebugBuild'" in Ionic 4 Cordova

Having trouble creating an Ionic 4 android app? Encountering a preDebugBuild error related to play-services-measurement-base and conflicting library versions? I've attempted various fixes including: - Running ionic repair - Reinstalling and updating ...

Issue when transmitting information from Angular to Express

I'm attempting to send data from Angular to Express.js Below is my TypeScript function connected to the button: upload(): void { const nameFromId = document.getElementById('taskName') as HTMLInputElement; this.taskName = nameFromI ...

What is the process for including a resource parameter in the acquireTokenSilent method of an MSAL instance within an Angular application?

const requestToken = { permissions: ['view_only'], }; newToken = await this.authInstance.acquireTokenSilent(requestToken); I'm trying to include the client ID of my Web API as a resource parameter when requesting the access token. Strugg ...

Creating an Angular 7 Template using HTML CSS and Javascript

I recently acquired a template that comes with HTML, CSS, and Javascript files for a static webpage. My goal is to integrate these existing files into my Angular project so I can link it with a Nodejs application to create a full-stack webpage with backend ...

Utilizing the 'as' prop for polymorphism in styled-components with TypeScript

Attempting to create a Typography react component. Using the variant input prop as an index in the VariantsMap object to retrieve the corresponding HTML tag name. Utilizing the styled-components 'as' polymorphic prop to display it as the select ...

Calculating the length of time based on a specific date in Angular 2+: A step-by-step

API: { data:{ "duration": 12, "startDate": "27-01-2020 16:09" } } I am currently working with Angular 2+. In the API response, the duration is set to 12 (in months) and the start date is provided as well... Task at hand: My goal is to ...

Trigger change event on model update in Angular 4 checkboxes

CSS <div class="checkbox-item"> <input type="checkbox" id="1" [(ngModel)]="filter" (change)="onFilterChange($event)"> CheckBox </div> <button (click)="filter = !filter">Change Status</button> JavaScript export class Filt ...

How can you expand the class of a library object in Animate CC using Createjs?

I am currently in the process of migrating a large flash application to canvas using Typescript, and I'm facing challenges when it comes to utilizing classes to extend library objects. When working with a class library for buttons, class BtnClass { ...

Retrieve the value of a property with a generic type

Within our angular6 project, we encountered an issue while using the "noImplicitAny": true setting. We realized that this caused problems when retrieving values from generic types. Currently, we retrieve the value by using current['orderBy'], bu ...

The service.subscribe function in Angular's Component Constructor is not functioning properly after the update

There are two components in my project, a parent and child component, and I am using a shared service to transfer data between them. The structure of the Service Class is as follows: export class AddItemDataTransferService { // Observable string sourc ...

Approach continuously activates database

The LanguageService class is injected into my components in order to retrieve translations for the component. When a key is not found in the Map, it fetches translations from the server and stores them in a Map. If the key is already in the Map, it retrie ...

Choose the appropriate data type for the class variable (for example, fArr = Uint32Array)

const functionArray: Function = Uint32Array; new fArr(5); The code snippet above is functioning properly. However, TypeScript is throwing a TS2351 error: "This expression is not constructable. Type 'Function' has no construct signatures". I wo ...

Establish a connection between an Angular client and a Spring backend using JWT for authentication

I successfully integrated JWT into my Spring backend by following the steps outlined in this informative guide: https://auth0.com/blog/securing-spring-boot-with-jwts/ Interestingly, when I perform a PUT request using Postman, everything seems to be workin ...

Leveraging an external TypeScript library in a TypeScript internal module

Imagine you find yourself in a situation where you need to utilize a typescript/node library within an internal module that is spanned across multiple .ts files. ApiRepositoryHelper.ts import * as requestPromise from "request-promise"; module ApiHelp ...