如何解决单元测试延迟加载的组件
我正在使用以下代码片段懒惰地加载组件及其模块:
@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) => {});
});
}
虽然此方法工作正常,但我不确定如何测试{{1}的输入(即组件获得data
)和发出的事件(即actionPerformed
事件) }。
在Angular 9之前,我猜想应该使用SpyNgModuleFactoryLoader,但是现在不建议使用NgModuleFactoryLoader。
您可以找到一个running example on StackBlitz。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。