angular - 如何在 Angular 组件的单元测试中提供 ControlContainer?

标签 angular typescript unit-testing angular-test ts-jest

根据标题,如何在 Angular 单元测试中提供 ControlContainer

以下是产生的错误:

NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]:
      StaticInjectorError(Platform: core)[ChildFormComponent -> ControlContainer]:
        NullInjectorError: No provider for ControlContainer!

我尝试提供ControlContainer:

  beforeEach(() => {
    const parentFixture = TestBed.createComponent(ParentFormComponent);
    const parentComponent = parentFixture.componentInstance;
    parentComponent.initForm();
    fixture = TestBed.createComponent(ChildFormComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

我见过其他使用以下方法的解决方案:

declarations: [
  ...MY_DECLARATIONS
],
imports: [
  ...MY_IMPORTS
],
providers: [
  {
    provide: ControlContainer,
    useValue: MyFormGroupDirective
  }
]

我运气不好,但如果这里有人能够提供一些线索;我将不胜感激。

最佳答案

我能够从这篇文章中得出解决方案:

How to mock ControlContainer in angular unit test?

我最终做的是:

let component: MyChildComponent;
let fixture: ComponentFixture<MyChildComponent>
let fg: FormGroup;
let fgd: FormGroupDirective;

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [ ...MY_DECLARATIONS ],
    imports: [ ...MY_IMPORTS ],
    providers: [
      { provide: ControlContainer, useValue: fgd }
    ]
  });

});

beforeEach(() => {
  const parentFixture = TestBed.createComponent(MyParentComponent);
  const parentComponent = parentFixture.componentInstance;
  fg = parentComponent.form;
  fgd = new FormGroupDirective([], []);
  fgd.form = fg;

  const childFixture = TestBed.createComponent(MyChildComponent);
  const childComponent = childFixture.componentInstance;

  childFixture.detectChanges();
});

我想做的是将初始化的父表单组附加到子表单组。

关于angular - 如何在 Angular 组件的单元测试中提供 ControlContainer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60940130/

相关文章:

C#单元测试代码题

css - 没有使用 Bootstrap for Angular 渲染的样式

html - 如何在 Angular 8 中创建动态网格组件并引导行、列和列表字符串?

javascript - Angular 6 +从文档中获取具有类名的元素并更改样式

angular - 如何从 angular cli 7.3.3 创建 angular 6 项目

javascript - 在 Typescript 中填充一个空的、类型化的对象

unit-testing - 在 VS 中为 typescript 运行单元测试

c# - 如何从另一个线程中止单元测试?

javascript - Angular 2 ionic 形式

java - Mockito 方法返回 null