Angular 2 TestModuleMetadata没有EntryComponents属性

Dan*_*lis 5 unit-testing typescript angular-cli angular

我正在使用Angular CLI 1.0.0-beta.32.2并正在为Angular 2服务编写单元测试,该服务动态创建一个Component并将其插入另一个Component.

在我的单元测试中,我尝试创建一个模拟组件来测试我的服务,但输出会ng test抛出一个错误,说明我的模拟组件是在entryComponents属性中指定的.当我尝试将Component添加到entryComponentsTestModuleMetadata对象的属性中时,如下所示:TestBed.createTestingModule({...entryComponents: [ TestDialogComponent ]...})我看到以下错误说明该entryComponents属性不存在.

Chrome 56.0.2924 (Windows 10 0.0.0) DialogService should create a child component when opening FAILED Error: No component factory found for TestDialogComponent. Did you add it to @NgModule.entryComponents?

查看TestModuleMetadata定义显示entryComponents属性不存在.那么如何在Angular 2和Jasmine的单元测试中动态创建一个Component呢?

yur*_*zui 16

据我所知,它还没有得到支持.作为解决方法,您可以创建假模块entryComponent并将其导入测试模块

@NgModule({
  imports: [CommonModule],
  declarations: [TestDialogComponent],
  entryComponents: [TestDialogComponent]
})
export class FakeTestDialogModule {}
Run Code Online (Sandbox Code Playgroud)

然后

TestBed.configureTestingModule({
    imports: [FakeTestDialogModule]
Run Code Online (Sandbox Code Playgroud)

  • 修好了,谢谢!我发现一个关于在TestModuleMetadata中省略了`entryComponents`属性的公开问题,[ComponentFactoryResolver不知道通过TestBed编译的组件](https://github.com/angular/angular/issues/10760) (2认同)