Ошибка Невозможно прочитать свойство «подписаться» из неопределенного, даже после шпионажа - PullRequest
0 голосов
/ 10 марта 2020

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

this.componentRef.instance.closeModal.subscribe(() => this.closeModal());

В моем методе тестирования я выполняю

 spyOn(component.componentRef.instance.closeModal, 'closeModal').and.returnValue(Observable.of(true));

Шпион, похоже, неверен.

fit('should call destroy ', () => {
    let childFixture: ComponentFixture<ExampleComponent>;
    childFixture = TestBed.createComponent(ExampleComponent);
    component.componentRef = childFixture.componentRef;
    spyOn(component.componentRef.instance.closeModal, 'closeModal').and.returnValue(Observable.of(true));
    spyOn(component.componentRef, 'destroy').and.callThrough();
    component.ngOnDestroy();
    expect(component.componentRef.destroy).toHaveBeenCalled();
  });

Компонент

export class ModalDialogComponent implements AfterViewInit, OnDestroy {
  private readonly _onClose = new Subject<any>();

  public componentRef: ComponentRef<any>;
  public childComponentType: Type<any>;
  public onClose = this._onClose.asObservable();

  // add this:
  @ViewChild(InsertionDirective, { static: false })
  insertionPoint: InsertionDirective;

  constructor(public componentFactoryResolver: ComponentFactoryResolver,
              public cd: ChangeDetectorRef,
              public dialog: ModalDialogRef) {
  }

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

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

  onOverlayClicked(evt: MouseEvent) {
    // close the dialog
  }

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

  loadChildComponent(componentType: Type<any>) {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
    const viewContainerRef = this.insertionPoint.viewContainerRef;
    viewContainerRef.clear();
    this.componentRef = viewContainerRef.createComponent(componentFactory);
    this.componentRef.instance.closeModal.subscribe(() => this.closeModal());
  }

  closeModal() {
    this.dialog.close();
  }
}

1 Ответ

0 голосов
/ 10 марта 2020

Попробуйте изменить область действия вашего заявления spyOn. В настоящее время он нацелен на closeModal из closeModal (дополнительно closeModal), которого не существует и, следовательно, он не работает корректно:

spyOn(component.componentRef.instance, 'closeModal').and.returnValue(Observable.of(true));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...