Búsqueda de sitios web

typescript - ¿Cómo proporciono ControlContainer dentro de la prueba unitaria de un componente de Angular?


Según el título, ¿cómo puedo proporcionar ControlContainer dentro de una prueba unitaria de Angular?

El siguiente es el error producido:

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

Mi intento de proporcionar ControlContainer:

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

He visto otras soluciones que utilizan:

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

No he tenido suerte, pero si hay alguien aquí que pueda arrojar algo de luz, lo apreciaría profundamente.

Respuesta #1

Pude derivar la solución de este post:

¿Cómo simular ControlContainer en una prueba unitaria de Angular?

Lo que terminé haciendo fue:

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

Lo que quería hacer era adjuntar el grupo de formularios principal inicializado al hijo.