Тестирование углового модуля с динамическим компонентом завершилось неудачно с ошибкой TypeError: невозможно прочитать свойство 'ɵcmp' из undefined

список угловых зависимостей

    "@angular/common": "~9.1.1",
    "@angular/compiler": "~9.1.1",
    "@angular/core": "~9.1.1",
    "@angular/forms": "~9.1.1",
    "@angular/platform-browser": "~9.1.1",
    "@angular/platform-browser-dynamic": "~9.1.1",
    "@angular/router": "~9.1.1",
    "@fortawesome/fontawesome-free": "^5.13.0"

dialogLayout.component.ts

import { Component, ViewChild, OnDestroy, AfterViewInit  } from '@angular/core';
import { ComponentFactoryResolver, Type, ComponentRef, ChangeDetectorRef } from '@angular/core';
import { Subject } from 'rxjs';

import { DynamicCompDirective } from '../../directive/dynamic-comp.directive';
import { DialogRef } from '../../model/dialog.ref';

@Component({
  selector: 'app-dialog-layout',
  templateUrl: './dialogLayout.component.html',
  styleUrls: ['./dialogLayout.component.css']
})
export class DialogLayoutComponent implements AfterViewInit, OnDestroy {

  @ViewChild(DynamicCompDirective, {static: true})insertionPoint: DynamicCompDirective;

  dialogHeight: number;
  dialogWidth: number;
  backDrop: boolean = false;

  public componentRef: ComponentRef<any>;
  public childComponentType: Type<any>;

  private readonly _onClose = new Subject<any>();
  public onClose = this._onClose.asObservable();


  constructor(private resolver: ComponentFactoryResolver,
              private cd: ChangeDetectorRef,
              private dialogRef: DialogRef) { }

  ngAfterViewInit() {
    this.loadChildComponent(this.childComponentType);
    this.cd.detectChanges();
  }

  ngOnDestroy() {
    if (this.componentRef) {
        this.componentRef.destroy();
    }
  }

  onOverlayClicked(evt: MouseEvent) {
    if (this.backDrop) {
      this.dialogRef.close();
    }
  }

  onDialogClicked(evt: MouseEvent) {
    evt.stopPropagation()
  }

  loadChildComponent(componentType: Type<any>) {
    const componentFactory = this.resolver.resolveComponentFactory(componentType);
    const viewContainerRef = this.insertionPoint.container;
    viewContainerRef.clear();
    this.componentRef = viewContainerRef.createComponent(componentFactory);
  }

  close() {
    this._onClose.next();
  }

}

dialogLayout.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ChangeDetectorRef } from '@angular/core';
import { DialogLayoutComponent } from './dialogLayout.component';
import { DialogRef } from '../../model/dialog.ref';

describe('DialogLayoutComponent', () => {
  let component: DialogLayoutComponent;
  let fixture: ComponentFixture<DialogLayoutComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ DialogLayoutComponent ],
      providers: [ { provide: DialogRef, useClass: DialogRef } ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(DialogLayoutComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

dialog.ref.ts

import { Observable, Subject } from 'rxjs';

export class DialogRef {

  constructor() {}

  private readonly _afterClosed = new Subject<any>();

  afterClosed: Observable<any> = this._afterClosed.asObservable();

  public close(result?: any): void {
    this._afterClosed.next(result);
  }

}

Мое модульное тестирование завершилось ошибкой TypeError: невозможно прочитать свойство "ɵcmp" of undefined

Понятия не имею, откуда эта ошибка. Уже потратил 2 дня на поиск в Google этой ошибки, но не повезло. Пожалуйста, помогите решить проблему.

введите здесь описание изображения

Заранее спасибо.


person luharatimarap    schedule 18.04.2020    source источник


Ответы (1)


Я предполагаю, что ваша ошибка исходит из dialogLayout.component.ts строки: const componentFactory = this.resolver.resolveComponentFactory(componentType);

Я бы установил там точку останова и убедился, что компонент действительно разрешается.

person Faraji Anderson    schedule 23.04.2020