Я пытаюсь шпионить за подпиской, но получаю ошибку Невозможно прочитать свойство 'подписка' из неопределенного. Я проверяю подписку в методе 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();
}
}