【问题标题】:Providing "entryComponents" for a TestBed为 TestBed 提供“entryComponents”
【发布时间】:2017-05-19 22:13:17
【问题描述】:

我有一个组件,它接收组件的组件类以作为子项动态创建。

let componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentToCreate);
this.componentReference = this.target.createComponent(componentFactory);

我正在尝试编写一个单元测试并传递一些 TestComponent 以供它创建和渲染。

TestBed
  .configureTestingModule(<any>{
    declarations: [MyAwesomeDynamicComponentRenderer, TestHostComponent],
    entryComponents: [TestComponent],
  });

因为configureTestingModule 期望TestModuleMetadata 没有entryComponents,所以有强制转换为“任何”,但我收到错误:“没有为TestComponent 找到组件工厂”。

如何将entryComponents 提供给TestBed

【问题讨论】:

    标签: javascript unit-testing angular


    【解决方案1】:

    好的,我想通了。在测试中,您应该定义新模块,在其中声明模拟组件并将其指定为 entryComponent

    @NgModule({
      declarations: [TestComponent],
      entryComponents: [
        TestComponent,
      ]
    })
    class TestModule {}
    

    并将其导入TestBed

    TestBed
      .configureTestingModule({
        declarations: [ValueComponent, TestHostComponent],
        imports: [TestModule],
      });
    

    希望对某人有所帮助:]

    【讨论】:

    • 如果 StackOverflow 能让你不止一次地为一个答案投票!
    • 我更喜欢这个而不是接受的答案,因为它使用与我的生产代码用于导入 NgModules 的相同机制。我也不需要知道overrideModule 方法做什么或不做什么。
    • 感谢您的回答,虽然老了。我的问题很相似,但我使用的是浅渲染器。我必须创建一个 testModule 并在那里提供一个入口组件,它在我正在编写的测试组件中使用。
    【解决方案2】:

    如果你愿意,你也可以直接在你的测试文件中做:

    import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing'; // DO not forget to Import
    
    TestBed.configureTestingModule({
      declarations: [ MyDynamicComponent ],
    }).overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [ MyDynamicComponent ],
      }
    });
    

    【讨论】:

    • 从'@angular/platform-b​​rowser-dynamic/testing'导入{ BrowserDynamicTestingModule };万一这对任何人都有帮助
    • 我们如何覆盖当前的模块定义 TestBed.configureTestingModule({...}) 以包含 entryComponents?我们是否必须按照另一个答案中的建议创建 TestModule 才能做到这一点?
    • @Jessycormier 我不确定你的问题。这基本上就是我在示例中所做的:我正在调用 overrideModule 方法,并通过 set 键提供一个新的 entryComponents 数组。如果你有其他组件,你可以用它创建一个数组,然后像这样设置 entryComponents:entryComponents: [ ...myComponentArray, MyDynamicComponent ]('...' 是 'Object.assign()' 的语法糖)
    • 我认为这是解决这个问题的正确答案,应该接受。
    • 我的 entryComponent 需要提供程序时出现 NullInjector 错误。
    猜你喜欢
    • 1970-01-01
    • 2018-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 2020-05-28
    • 2017-08-17
    • 1970-01-01
    相关资源
    最近更新 更多