An issue occurred: 'Problem encountered while cleaning up component', Object{component: FilterComponent}

When running the test for FilterComponent, I keep encountering this error:

Error

'Error during cleanup of component', Object{component: FilterComponent{lang:
     Language{cookie: ..., get: ..., getLocale: ..., dict: ...}, api: Api{http:
     ..., router: ..., cookie: ..., send: ..., setUrl: ...}, filterService: 
    FilterService{update: ..., filter: ...}, searchbar: SearchbarService{}, 
    localStorageCache: LocalStorageCache{api: ...}, cookie: CookieService{document: 
    ..., optionsProvider: ..., cookieWriterService: ..., options: ...}, formatter: 
    NgbDateISOParserFormatter{}, calendar: NgbCalendarGregorian{}, onFilter: 
    EventEmitter{_isScalar: ..., observers: ..., closed: ..., isStopped: ..., hasError:
     ..., thrownError: ..., __isAsync: ...}, category: '', search: Subject{_isScalar: 
    ..., observers: ..., closed: ..., isStopped: ..., hasError: ..., thrownError: ...}, 
    selectedElems: [], hoveredDate: null, filterDef: Object{tweets: ..., news: ..., events:
     ..., dashboard: ..., dashboardHashtags: ..., people: ..., reports: ..., editorials: 
    ..., verdicts: ..., organizations: ..., results: ..., _dashboard: ...}, componentDict: 
    Object{author: ..., people: ..., organizations: ..., tag: ..., tactics: ..., court: 
    ..., pillars: ..., hashtags: ..., magistrates: ..., website: ...}, yearRange: [..., ...],
     getPillars: () => { ... }, dateFromNgbDate: ngbDate => { ... }, isEmpty: () => { ... }, 
    getElements: () => { ... }, addItem: item => { ... }, compareIds: (el1, el2) => { ... },
     clearItem: item => { ... }, fillMultiSelect: () => { ... }, relevantChange: $ev => { 
    ... }, user: Object{id: ..., username: ..., name: ..., role: ..., id_client: ..., 
    language: ..., filter: ..., services: ...}, __ngContext__: [..., ..., ..., ..., ..., 
    ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., 
    ..., ..., ..., ..., ..., ..., ..., ..., ...], filterObj: Object{date_range: ..., 
    relevant: ...}}, stacktrace: TypeError: Cannot read properties of undefined (reading 'unsubscribe')
    TypeError: Cannot read properties of undefined (reading 'unsubscribe')

    

I have made sure to import all necessary components in the spec file configuration.

filterComponent

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';

    export interface MultiSelectItem {
        id: number,
        name: string,
        type: string
    }

    @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>();

        // Rest of the code goes here...

    

Despite importing and configuring everything needed in the ts file, the ng test command continues to fail. Help required.

SPEC:

// Test cases go here...
    

Answer №1

Your error occurs in the ngOnDestroy function because your subscription variables are not being assigned in your tests. To solve this issue, you have a couple of options. You can either initialize your subscriptions immediately like so:

updateFilterSubscription = new Subscription();

and then add your subscription using:

this.updateFilterSubscription.add(<your_subscription>);

Alternatively, in your ngOnDestroy function, you can first check if the subscriptions exist using the ? operator or an if statement, and then unsubscribe as follows:

this.updateFilterSubscription?.unsubscribe();

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

Troubleshooting errors in a Vue.js TypeScript project using WebStorm, the debugger fails to halt at designated break points

I recently started a new project in WebStorm using TypeScript settings, but for some reason the debugger break point isn't working. My configuration Version Node 12.10 Vue/CLI 3.11.0 Project setup Babel TypeScript Router CSS Pre-processors Uni ...

An iron-dropdown made of polymer featuring a trigger button made of paper-icon-button

I am facing an issue on my Angular site where I have integrated Polymer. I am trying to add a notifications section to the header, but I am struggling to make the button functional. How can I bind the click event of the button to trigger the dropdown? Thi ...

The Ionic framework lacks support for the firebase and auth properties found in Firebase

Currently, I am developing a user-generated content feature along with buttons using ionic 5 and integrating it with the firebase app. I have been studying posts to incorporate them into my application. I am utilizing: "firebase": "^8.1.1&q ...

Invoke the REST API when a checkbox is selected

I have a React component that I need help with: import * as React from 'react'; import './Pless.css'; interface Props { handleClose: () => void; showPless: boolean; } export class Pless extends React.Component<Props> ...

Import a JSON file into Angular 8 and parse its contents

My code is intended to read and upload a JSON file (ARM template), but I am encountering an issue where this.updateObj appears as undefined in the console.log. Below is my code: onChange(fileList: FileList): void { var file = fileList[0]; var fileR ...

Exclude the bundled .d.ts files and opt for external declarations instead

I am endeavoring to implement the validate.js library, which comes with its own TypeScript declaration file. However, the provided typing for the library is not very accurate, and there is a more superior one available in DefinitelyTyped. Despite installi ...

Issue TS2322 presents itself when attempting to assign a value of type 'string, number, or Date' to a variable of type 'Date' after upgrading to Angular 16

I recently upgraded my project from Angular 11 to Angular 16 and encountered an issue with the DTO models generated using the NPM package "ng-swagger-gen" from the Swagger JSON file of the Web API. In my C# class on the Web API side, I have a DateTime fiel ...

The parameter type 'string | null' cannot be assigned to the argument type 'string'. The type 'null' is not compatible with the type 'string'.ts(2345)

Issue: The parameter type 'string | null' is not compatible with the expected type 'string'. The value 'null' is not a valid string.ts(2345) Error on Line: this.setSession(res.body._id, res.headers.get('x-access-token&ap ...

I'm encountering an error stating that a property does not exist for Twilio.Response() while attempting to convert a Twilio CORS Node.js example to TypeScript. Can anyone shed

In my current project, I am converting a CORS Node.js example from Twilio's documentation into TypeScript. Here is the original Node.js code: exports.handler = (context, event, callback) => { const client = context.getTwilioClient(); const resp ...

Manually initiating event broadcasts in Angular 5

After researching, I discovered a solution for implementing $broadcast and $on in Angular 5. It involves creating a custom service called broadcaster. I have two parallel components that need to listen for change events triggered by the parent component. ...

What is the correct way to implement "next-redux-wrapper" with "Next.js", "Redux-ToolKit" and Typescript?

Currently, I am integrating RTK (redux-toolkit) into my Next.js App. I am facing an issue while trying to dispatch an AsyncThunk Action within "getInitialProps". During my research, I came across a package named "next-redux-wrapper" that allows access to t ...

Combining default and named exports in Rollup configuration

Currently, I am in the process of developing a Bluetooth library for Node.js which will be utilizing TypeScript and Rollup. My goal is to allow users to import components from my library in various ways. import Sblendid from "@sblendid/sblendid"; import S ...

Downloading in Angular 9 is restricted. The frame responsible for starting the download is sandboxed; however, the 'allow-downloads' flag is not enabled

Hey everyone :) There's a warning popping up in the console when I attempt to download a file within the application: Download is disallowed. The frame initiating or instantiating the download is sandboxed, but the flag ‘allow-downloads’ is not s ...

The subcategory was not factored into my npm package

In my npm module 'ldap-pool', I'm facing an issue where the '@types/ldapjs' package, which is a dependency along with 'ldapjs', does not get installed when I add 'ldap-pool' to another project. This particular s ...

TypeORM does not have the capability to specify the database setting within the entity decorator

As my TypeORM project grows in size and its components become more discreet yet interconnected, I am exploring ways to separate it into multiple databases while maintaining cross-database relations. To achieve this, I have been experimenting with the data ...

Angular: Array in the template re-renders even if its length remains unchanged

Below is the template of a parent component: <ng-container *ngFor="let set of timeSet; index as i"> <time-shift-input *ngIf="enabled" [ngClass]="{ 'mini-times' : miniTimes, 'field field-last&ap ...

Tips for creating a type-safe union typed save method

My goal is to build a versatile http service that includes a method like save(value), which in turn triggers either create(value) or update(value). What sets this requirement apart is the optional configuration feature where the type of value accepted by c ...

You can't access global variables within spec files in Protractor testing

When trying to automate an Angular 4 app, I encountered the need to declare some global variables like myVar = 'John'. I attempted to declare it in protractor.conf but unfortunately, it did not work. Even after exploring solutions on Protractor s ...

How can one locate exclusively unused JSDoc type definitions?

For instance: /** * A boolean value. * @typedef {boolean} BoolType * * Another dummy type definition. * @typedef {(number|string)} SomeType */ /** * Set the boolean flag. * @param {BoolType} flag - The bool flag value. */ function setFlag(flag) { ...

Stop VueJs RouterView's Transitions from triggering on carousel initialization

As I dive into the world of VueJs (3), I've implemented a transition effect on my routes to give my pages a smooth appearance. Everything seems to be working well, but there's one issue - when I refresh the page (F5) or on first load, the transit ...