Unable to execute karma test cases as a result of ngOnDestroy being inaccessible

I have a component structured as follows:

export class InkbarComponent implements AfterViewInit, OnDestroy {
    resizeListener: any;

    constructor(private _renderer: Renderer, private _elementRef: ElementRef, public renderer: Renderer) { }
    ngAfterViewInit() {
        this.resizeListener = this.renderer.listenGlobal('window', 'resize', (event) => {
            if (this.currentElement) {
                this.switchPostion(this.currentElement);
            }
        });
    }
    public switchPostion(element: HTMLElement) {
        // function logic
    }


    ngOnDestroy() {
        this.resizeListener();
    }
}

However, when I use this component in another component, Karma test cases start to fail.

The error message reads:

Error: Error in ./TabContainerComponent class TabContainerComponent - inline template:2:2 caused by: this.resizeListener is not a function
TypeError: this.resizeListener is not a function
    at InkbarComponent.ngOnDestroy (webpack:///src/components/basic-components/ink-bar/inkbar.component.ts:9:4753 <- src/tests.entry.ts:117472:4760)
    at Wrapper_InkbarComponent.ngOnDestroy (/WebBasicModule/InkbarComponent/wrapper.ngfactory.js:13:16)
    at CompiledTemplate.proxyViewClass.View_TabContainerComponent0.destroyInternal (/DynamicTestModule/TabContainerComponent/component.ngfactory.js:342:29)
    at CompiledTemplate.proxyViewClass.AppView.destroy (webpack:///~/@angular/core/bundles/core.umd.js:12362:0 <- src/tests.entry.ts:23410:19)
    at CompiledTemplate.proxyViewClass.DebugAppView.destroy (webpack:///~/@angular/core/bundles/core.umd.js:12717:0 <- src/tests.entry.ts:23765:43)
    at CompiledTemplate.proxyViewClass.View_TabContainerComponent_Host0.destroyInternal (/DynamicTestModule/TabContainerComponent/host.ngfactory.js:43:19)
    at CompiledTemplate.proxyViewClass.AppView.destroy (webpack:///~/@angular/core/bundles/core.umd.js:12362:0 <- src/tests.entry.ts:23410:19)
    at CompiledTemplate.proxyViewClass.DebugAppView.destroy (webpack:///~/@angular/core/bundles/core.umd.js:12717:0 <- src/tests.entry.ts:23765:43)
    at CompiledTemplate.proxyViewClass.AppView.detachAndDestroy (webpack:///~/@angular/core/bundles/core.umd.js:12346:0 <- src/tests.entry.ts:23394:19)
    at ComponentRef_.destroy (webpack:///~/@angular/core/bundles/core.umd.js:7646:55 <- src/tests.entry.ts:18694:75)

This issue arises because the resizeListener is not being recognized as a function in the ngOnDestroy method.

As a result, numerous errors are occurring.

Answer №1

Prior to invoking the resizeListener property, ensure that it is defined.

Alternatively, you may implement the following:

@HostListener('window:resize', ['$event'])
onWindowResize(event) {
    if (this.currentElement) {
        this.switchPostion(this.currentElement);
    }
}

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

Searching for two variables in an API using TypeScript pipes

I'm stuck and can't seem to figure out how to pass 2 variables using the approach I have, which involves some rxjs. The issue lies with my search functionality for a navigation app where users input 'from' and 'to' locations i ...

Services that are not configured as singleton instances

In my view, I am utilizing a file upload component multiple times. Each uploading file is managed by a service that handles its metadata. However, when I add files to one component, all the components begin updating instead of just the intended one. Is it ...

Encountering a problem with npm while trying to initialize a new Angular project causes

I encountered an issue while attempting to create a new Angular project using Git Bash console with the ng new command. I have successfully created projects in the past without any problems. For more information, please refer to the debug log here and th ...

Exploring Angular5 Testing Utilizing Jasmine: A Component Found in Both the AppModule and DynamicTestModule's Declarations

Currently, I'm working on writing my initial test and facing a specific error: An error stating that Type SearchComponent is part of the declarations of 2 modules – AppModule and DynamicTestModule. The suggestion is to consider moving SearchCompo ...

A guide on utilizing NgFor for a standalone element

I am working with a component that interacts with a service to make REST calls. The code for the API service looks like this: api.service import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; i ...

Revealing a single element in an Angular 6 application that is utilized by several modules

As I am in the process of breaking down a large module into smaller ones, I have encountered an issue that needs to be addressed. Here are the specifics: The Search component is currently being used across multiple components. Initially, it was declared i ...

We are unable to update the document in AngularFire as the document reference ID could not be retrieved

I am currently working on an update function that is designed to retrieve a specific document based on its unique document uid, which is connected to the authenticated user's uid. In another part of my code, I have a function that successfully fetche ...

Encountering CORS Issue with Golang and Gin following a Redirect Situation

I am currently working on implementing Google OAuth2 in my Go web server using Gin. I have integrated two new endpoints - /google/sign-in and /google/callback. The former receives the request and redirects to the Google auth URL, while the latter is trigge ...

The parameter '{ validator: any; }' cannot be assigned to the ValidatorFn type in this context

I am currently experiencing a challenge while attempting to create a custom validator using Angular. I have created a form for my sign-up page and wanted to ensure that the password and confirm password fields match by implementing a custom validator. Des ...

Setting up *ngFor with a freshly created array_INITIALIZER

Angular v5 In my search component, I am encountering an issue where the *ngFor directive is throwing an error because the "searchResults" array is initially empty on page load. This array is populated with data from a service returning a promise of search ...

Update a BehaviourSubject's value using an Observable

Exploring options for improving this code: This is currently how I handle the observable data: this.observable$.pipe(take(1)).subscribe((observableValue) => { this.behaviourSubject$.next(observableValue); }); When I say improve, I mean finding a wa ...

Retrieving information from an http request within a for loop in an Angular 2+ application

I have a scenario where I need to call my http request inside a for loop in order to process 1000 items at a time. Here's the code snippet that implements this logic: getData(IDs: string[]): Observable<any> { // IDs is a large array of strin ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

Capable of retrieving response data, however, the label remains invisible in the dropdown menu

Upon selecting a country, I expect the corresponding city from the database to be automatically displayed in the dropdown menu. While I was able to retrieve the state response (as seen in the console output), it is not appearing in the dropdown menu. Inte ...

The type definition file for 'node' cannot be located

I've encountered some unusual errors after updating angular, webpack, and typescript. Any suggestions on what might be causing this? When I attempt to run the application with npm start, I'm seeing the following errors: [at-loader] Cannot find ...

Can dynamic forms in Angular 2 support nested forms without relying on formBuilder?

I'm familiar with implementing nested forms in reactive form, but I'm unsure about how to do it in dynamic form within Angular 2. Can nested forms be implemented in dynamic forms in Angular 2? ...

Getting a specific piece of information from a JSON file

I am encountering an issue with my JSON file collection. When I access it through http://localhost:5000/product/, I can see the contents without any problem. However, when I try to retrieve a specific product using a link like http://localhost:5000/product ...

Typescript with Angular: Despite having 7 values in the map, Map.get is returning undefined

Why does Map.get always return undefined when using a number from a form element (extra1) in this code snippet? extraById = new Map<number,Extra>(); @Input() extra1: number = -1; formChanged(carConfigurationFormChanged : any) { const index ...

The 'Access-Control-Allow-Origin' header can be found on the resource that was requested

I'm facing an issue while trying to connect my .net core API to an Angular application. Whenever I attempt to do so, I encounter the following error: Access to XMLHttpRequest at 'https://localhost:44378/api/recloadprime' from origin 'h ...

Ways to update index.html in Angular 8.3+ based on the current environment settings

I am currently developing an application using jhipster, Spring Boot, and Angular. One challenge I am facing is setting up different public keys based on whether the app is running in a development or production environment. I have spent a considerable a ...