0

我正在使用以下代码片段懒惰地加载一个组件及其模块:

@ViewChild(TemplateRef, { read: ViewContainerRef })
private templateViewContainerRef: ViewContainerRef;

constructor(
  private readonly componentFactoryResolver: ComponentFactoryResolver,
  private readonly injector: Injector
) {}

ngOnInit() {
  this.loadModuleAndComponent();
}

private async loadModuleAndComponent() {
  import('@scope/package').then(({ LazyModule, LazyComponent }) => {
    // load module to set up store etc.
    createInjector(LazyModule, this.injector).get(LazyModule);

    // create component instance
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(LazyComponent);
    const componentRef = this.templateViewContainerRef.createComponent(componentFactory);
  

    // set data of the component
    // how to test?
    componentRef.instance.data = {};

    // handle emitted events
    // how to test?
    componentRef.instance.actionPerformed
      .asObservable()
      .pipe(take(1))
      .subscribe((action) => {});
  });
}

虽然这工作正常,但我不确定如何测试该组件中的输入(即组件 got data)和发出的事件(即actionPerformed事件)LazyComponent

在 Angular 9 之前,我想使用SpyNgModuleFactoryLoader是可行的方法,但NgModuleFactoryLoader现在已被弃用。

您可以在 StackBlitz 上找到一个运行示例

4

0 回答 0