An error was thrown in afterAll TypeError: Cannot read properties of undefined (reading 'toLowerCase')
Asked Answered
G

2

5

I was making my spec file and setting but sometimes this error appears in the console 'An error was thrown in afterAll TypeError: Cannot read properties of undefined (reading 'toLowerCase')',

Why does this error appear?.

This is my 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 import all necesary from component, this 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();
    }
}
Garrulity answered 11/8, 2021 at 15:23 Comment(1)
It may be because of the constructor. Not sure but you can try this: Instead of JSON.parse(this.cookie.get('user')), try having this: JSON.parse(JSON.stringify(this.cookie.get('user'))). I maybe wrong but it doesnt help to try once i guess.Loess
N
6

I had similar problem running all test at once. If run one by one then I don't see this error. So I added the following line of code at each test method end

fixture.destroy();

In your case, try calling the destroy method at the end of test method.

Neel answered 15/10, 2021 at 13:57 Comment(0)
K
0

Static template strings

were the issue for me. My code before:

export class MyClass {
  static NAME = "Cool-Name";
  static DESC = `This is ${MyClass.NAME}!`;
}

Fixed code:

export class MyClass {
  static NAME = "Cool-Name";
  static get DESC() { return `This is ${MyClass.NAME}!`; }
}

Explanation: This issue is due to the way static fields are initialized in JavaScript. When DESC is being defined, NAME may not have been initialized yet, leading to the error. However, it's interesting that this error never occurred to me outside of testing.

Kissie answered 22/1, 2024 at 20:4 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.