A mistake occurred during the afterAll function, resulting in a TypeError: Unable to access properties of an undefined entity (specifically, trying to read '

While creating my spec file and settings, I encountered an error in the console: 'An error was thrown in afterAll TypeError: Cannot read properties of undefined (reading 'toLowerCase')',

What could be causing this error to appear?

Here is the configuration in my spec file:

import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from "@angular/core";
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from "@angular/core/testing";
import { FilterComponent } from "./filter.component";
import { RouterTestingModule } from '@angular/router/testing';
import { CookieModule, CookieService } from 'ngx-cookie';
import { Api } from '../../services/api.service';

fdescribe('filter Component', () => {
  let component: FilterComponent;
  let fixture: ComponentFixture<FilterComponent>;
  let service: Api;
  let filterService: FilterService;
  let cookieService: CookieService;

  beforeEach(() => {
    TestBed.configureTestingModule({
        imports: [
            HttpClientTestingModule,
            RouterTestingModule,
            CookieModule.forRoot()
        ],
        declarations: [
            FilterComponent,
        ],
        providers: [
          Api,
          CookieService,
          FilterService
        ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
    }).compileComponents();
  });

  beforeEach(() => {
    cookieService = TestBed.inject(CookieService);
    cookieService.put('user', JSON.stringify(user));
    fixture = TestBed.createComponent(FilterComponent);
    component = fixture.componentInstance;
    service = TestBed.inject(Api);
    filterService = TestBed.inject(FilterService);
    component.ngOnInit();
  });

  afterEach(() => {
    component.ngOnDestroy();
    component = null;
    fixture = null;
    service = null;
    filterService = null;
    cookieService = null;
  });

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

  describe('ngOnInit()', () => {
    it('Should call clearFilter()', () => {
      let spy1 = spyOn(component, 'clearFilter');
      component.ngOnInit();
      expect(spy1).toHaveBeenCalled();
    });
  });
});

I have imported all necessary components for this project. Here is my TypeScript file:

import { Component, Input, Output, EventEmitter, OnInit, OnDestroy } from '@angular/core';
import { Language } from '../../services/language.service';
import { Observable, concat, of, Subject, Subscription } from 'rxjs';
import { distinctUntilChanged, switchMap, filter } from 'rxjs/operators';
import { CookieService } from 'ngx-cookie';

import { Api } from '../../services/api.service';
import { FilterService } from '../../services/filter.service';
import { LocalStorageCache } from '../../services/local-storage-cache.service';
import * as _ from 'lodash';
import { SearchbarService } from '../../services/searchbar.service';
import { NgbDate, NgbCalendar, NgbDateParserFormatter } from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'is-filter',
    templateUrl: './filter.component.html',
    styleUrls: ['./filter.component.scss']
})
export class FilterComponent implements OnInit, OnDestroy {
    @Input() type: string;
    @Input() filterObj: any;

    @Output() onFilter: EventEmitter<any> = new EventEmitter<any>();

    category: string = '';
    search: Subject<string> = new Subject<string>();
    selectedElems: MultiSelectItem[] = [];
    hoveredDate: NgbDate | null = null;

    constructor(
        public lang: Language,
        private api: Api,
        public filterService: FilterService,
        public searchbar: SearchbarService,
        public localStorageCache: LocalStorageCache,
        private cookie: CookieService,
        public formatter: NgbDateParserFormatter,
        private calendar: NgbCalendar
    ) {
        this.user = JSON.parse(this.cookie.get('user'));
    }

    updateFilterSubscription: Subscription;
    filterSubscription: Subscription;

    ngOnDestroy() {
        this.updateFilterSubscription.unsubscribe();
        this.filterSubscription.unsubscribe();
    }

    ngOnInit() {
        this.clearFilter();
        this.filter();

        this.updateFilterSubscription = this.filterService.update.subscribe((componentFilter: object) => {
            this.clearFilter();
            this.filterObj = { ...this.filterObj, ...componentFilter };
            if (componentFilter && this.type != 'verdicts') {
                this.category = ['date_range', 'affinity', 'affinity_u', 'relevant', 'country'].indexOf(Object.keys(componentFilter)[0]) !== -1 ? 'people' : Object.keys(componentFilter)[0];
            }
            this.fillMultiSelect()
        });
        this.filterSubscription = this.filterService.filter.subscribe(() => {
            this.filter();
        });
        this.getPillars();
    }
}

Answer №1

I encountered a similar issue when running all tests simultaneously. However, when I ran them one by one, the error did not appear. To address this, I included the line of code below at the conclusion of each test method:

fixture.destroy();

In your situation, consider invoking the destroy method at the end of each test method.

Answer №2

Dynamic template literals

were causing problems in my code. Here's what I had before:

export class Example {
  static MSG = "Hello World";
  static TEXT = `Greetings from ${Example.MSG}!`;
}

Here's the updated version that fixed the issue:

export class Example {
  static MSG = "Hello World";
  static get TEXT() { return `Greetings from ${Example.MSG}!`; }
}

Explanation: The error was occurring because of how static fields are initialized in JavaScript. As DESC tried to reference NAME, it wasn't guaranteed that NAME had already been initialized. Surprisingly, this bug only surfaced during testing and not in production code.

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

"Choose one specific type in Typescript, there are no in-b

Need help returning an object as a fetch response with either the property "data" or "mes": { data: Data } | { mes: ErrMessage } Having trouble with TypeScript complaining about this object, let's call it props: if (prop.mes) return // Property &a ...

What is the classification of the socket entity?

After searching through various posts, I couldn't find a solution to my problem so I decided to create my own thread. The issue I'm facing is determining the correct type for the 'socket' instance that I'm passing as a prop to my ...

Warning: Unresolved promise: NullInjectorError encountered: StaticInjectorError(AppModule) when trying to use FormBuilder

I encountered an error in my Angular app when adding routes in gifts-routing.module.ts. The error disappears when I remove the routes, but I still need to implement routing. How can I resolve this issue? ERROR Error: Uncaught (in promise): NullInjectorErr ...

Upon being redirected to a different route, it immediately navigates back to the previous page

Whenever we redirect to a route using an anchor tag with [routerLink], or through the code using: router.navigate(['/path']) For example, if we redirect to the extractedData page from the result page, it initially shows the extractedData page b ...

Incorrect Column Header Display in React with Kendo-UI Grid

I have a React application using redux as state manager. In this application we are deciding to use Kendo Ui grids. The first test is Ok but we noticed that the columns are totally wrong. We define only 5 Columns to be displayed in the table but we noticed ...

What are the steps to configure Angular to run with https instead of the default http protocol?

Typically, Angular applications run on http by default (for example, on http://localhost:4200). Is there a way to switch it from http to https? ...

does not have any exported directive named 'MD_XXX_DIRECTIVES'

I am currently learning Angular2 and I have decided to incorporate angular material into my project. However, I am encountering the following errors: "has no exported member MD_XXX_DIRECTIVES" errors (e.g: MD_SIDENAV_DIRECTIVES,MD_LIST_DIRECTIVES). Her ...

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 ...

The Angular2 framework will sometimes send an OPTIONS method request instead of an http.GET when

I am currently attempting to implement basic authentication in my Angular2 application. public login() { // Setting basic auth headers this.defaultHeaders.set('Authorization', 'Basic ' + btoa(this.username + ':' + thi ...

Creating a Session Timeout feature for Ionic/Angular that includes resetting the timer with each new user interaction

Having trouble implementing a session timeout feature in my code. I need the timer to reset whenever a user interacts with the function. Can't figure out how to integrate similar code like the one provided as an example on Stack Overflow. This is the ...

Utilizing dual functions within the onChange event handler in React

I have a situation where I need to pass a function from a parent component to a child component through the onChange event, as well as another function in the child component to update its own state. How can I achieve this? Parent export function Fruits() ...

Angular 2: Implementing service functions on button click using the (click) event

Is it possible to call a function from my service when clicking on an element in the HTML returned from an HTTP call? Here is the HTML snippet: <a (click)="SellingVarietiesService.goToVarietyDetails(3)">Test</a> The function I want to call i ...

Using async/await does not execute in the same manner as forEach loop

Here is a code snippet that I have been working with. It is set up to run 'one' and then 'two' in that specific order. The original code listed below is functioning correctly: (async () => { await runit('one').then(res ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

Creating an array with varying types for the first element and remaining elements

Trying to properly define an array structure like this: type HeadItem = { type: "Head" } type RestItem = { type: "Rest" } const myArray = [{ type: "Head" }, { type: "Rest" }, { type: "Rest" }] The number of rest elements can vary, but the first element ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

How to eliminate file nesting in Visual Studio 2017

Is there a way to prevent certain file types from being nested within other files, such as .ts files not being nested beneath .html files? I came across this request, but has anyone found a solution to achieve this? ...

Strategies for extracting the type argument from a nested property and transforming it into a different value

I’m struggling to find the right way to frame my question, so I’ll provide an example of what I need help with. Let's assume I have the following object: const obj = { one: 'some string', two: new Set<string>(), }; Now, I wan ...

Cultural adaptation in Angular

I have successfully created an Angular project with internationalization capabilities. However, I am now looking to implement it by culture, such as es-AR or en-NZ. Below are my configurations for Spanish and English in the angular.js file: "build": { ...

Troubleshooting spacing problems in Angular Material tables

I'm attempting to utilize an Angular Material table in the following way: <div class="flex flex-col pb-4 bg-card rounded-2xl shadow overflow-hidden"> <table mat-table class="" [dataSource]="$candidates ...