在angular6中测试ViewContainerRef

时间:2019-02-24 16:58:20

标签: angular

嗨,我使用viewContainerRef动态添加了组件。

export class DynamicComponentHolderComponent implements OnInit {

  comp: CompItem;
  @ViewChild(CompDirective) compHost: CompDirective;

  customUiList: Array<CompItem> = [];

  componentRef: any;

  constructor(
    public dialog: MatDialogRef<DynamicComponentHolderComponent>,
    @Inject(MAT_DIALOG_DATA) public receivedData: any,
    private componentFactoryResolver: ComponentFactoryResolver,
    private _componentService: CompService
  ) {
  }

  ngOnInit() {
    console.log(JSON.stringify(this.receivedData));
    this.getCustomComponentList();
  }

  loadComponent() {
    const dynamicItem = this.comp;

    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(dynamicItem.component);

    const viewContainerRef = this.compHost.viewContainerRef;
    viewContainerRef.clear();

    this.componentRef = viewContainerRef.createComponent(componentFactory);
    (<CompComponent>this.componentRef.instance).data = this.receivedData.data;


    <CompComponent>this.componentRef.instance.
    updateEmitter.subscribe((response) => {
    this.dialog.close({ confirm: true, orderid: response.orderId, orderNumber: response.orderNumber });
    });

    // Default Close Emitter
    <CompComponent>this.componentRef.instance.
      closeEmitter.subscribe((response) => {
        this.closeDialog('close');
      });

  }

  getCustomComponentList() {
    this._componentService.getComponents()
      .subscribe(
        (response) => {
          if (response.length > 0) {
            response.forEach((comp) => {
              this.customUiList.push(comp);
            });
            const classNameIndex = _.findIndex(this.customUiList, (o) => {
              return o.data.displayName == this.receivedData.data.customComponent;
            });
            console.log('FROM COMP', this.customUiList);
            if (classNameIndex > -1) {
              this.comp = this.customUiList[classNameIndex];
              this.loadComponent();
            }
          }
        }
      );
  }

  ngOnDestroy() {
  }

  closeDialog(param: any) {
    <CompComponent>this.componentRef.destroy();
    this.dialog.close({ confirm: false });
  }


}

现在我要测试this.componentRef.destroy();。我该如何在我的spec.ts文件中做到这一点。我不知道该怎么做。需要帮助。

1 个答案:

答案 0 :(得分:0)

如果您已经熟悉了角度测试,那么测试DOM(用户界面)中某些内容的最佳选择是使用组件DOM测试GetCursorPos

如果您以前从未做过测试,强烈建议您阅读System.Drawing.Point,了解如何设置角度测试的基础。

希望这会有所帮助!