【问题标题】:How do I provide ControlContainer inside an Angular component's unit test?如何在 Angular 组件的单元测试中提供 ControlContainer?
【发布时间】:2020-03-31 08:54:11
【问题描述】:

根据标题,如何在 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
  }
]

我没有运气,但是如果这里有任何人能够提供一些启示;我将不胜感激。

【问题讨论】:

  • 你是否包含了相关的表单模块?
  • @jonrsharpe 是的,ReactiveFormsModuleFormsModule 已导入。还是不行。

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


【解决方案1】:

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

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();
});

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

【讨论】:

    猜你喜欢
    • 2019-06-05
    • 2019-02-10
    • 2018-08-04
    • 2018-06-21
    • 2022-01-03
    • 2017-08-13
    • 2015-03-04
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多