【问题标题】:An error was thrown in afterAll TypeError: Cannot read properties of undefined (reading 'toLowerCase')afterAll TypeError 中引发错误:无法读取未定义的属性(读取“toLowerCase”)
【发布时间】:2021-10-15 01:57:00
【问题描述】:

我正在制作我的规范文件并进行设置,但有时控制台中会出现此错误“在 afterAll TypeError 中引发错误:无法读取未定义的属性(读取 'toLowerCase')”,

为什么会出现这个错误?

这是我在我的规范文件中的配置:

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

我从组件中导入所有必需品,这是我的打字稿文件:

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

【问题讨论】:

  • 可能是构造函数的原因。不确定,但你可以试试这个:而不是JSON.parse(this.cookie.get('user')),试试这个:JSON.parse(JSON.stringify(this.cookie.get('user')))。我可能错了,但是一旦我猜到了尝试也没有用。

标签: angular typescript karma-jasmine


【解决方案1】:

我在一次运行所有测试时遇到了类似的问题。如果一个一个运行,那么我看不到这个错误。所以我在每个测试方法末尾添加了以下代码行

fixture.destroy();

在你的情况下,尝试在测试方法结束时调用destroy方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2022-09-12
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多