使用 viewProvider 测试组件

Test component with viewProvider

@Component({
  selector: 'app-entity-details',
  templateUrl: './entity-details.component.html',
  styleUrls: ['./entity-details.component.scss'],
  viewProviders: [{
    provide: ControlContainer,
    useFactory: (container: ControlContainer) => container,
    deps: [[new SkipSelf(), ControlContainer]],
  }]
})
export class EntityDetailsComponent{

我发现上述设置在我的组件上使用 viewProviders 作为一种在 nestes 组件中使用嵌套 Formgroup 的方式,而无需手动处理它们作为输入 and/or 输出。现在我想弄清楚如何在规范文件中设置我的测试环境。

目前我显然收到“找不到 'ControlContainer' 的提供商”错误。配置 TestingModule 以提供与我使用的完全相同的东西,甚至是通用的 ControlContainer 也不会产生任何结果。我是否必须模拟一个使用我的 EntityDetailsComponent 的新组件?

感谢任何可能有帮助的资源。

编辑

首先看看这个,我认为它可以帮助你更多。

编辑结束

尝试模拟它:

let mockControlContainer;
....
// This (mockControlerContainer = ) should be at the beginning of your first beforeEach
// The first string is the identifier (can be anything) and the second array of strings
// are public methods you would like to mock for ControlContainer.
// I put 'public', 'methods' but you can change them to anything you like.
mockControlContainer = jasmine.createSpyObj('container', ['public', 'methods']);
...
TestBed.configureTestingModule({
  imports: [], // put in imports what is needed
  declarations: [EntityDetailsComponent],
  // provide the mockControlContainer
  providers: [{ provide: ControlContainer, useValue: mockControlContainer }]
});

如果ControlContainer没有任何依赖,很容易被mock,你应该可以直接提供:

TestBed.configureTestingModule({
  imports: [], // put in imports what is needed
  declarations: [EntityDetailsComponent],
  // provide the mockControlContainer
  providers: [ControlContainer]
});