简体   繁体   中英

How do I provide ControlContainer inside an Angular component's unit test?

As per the title, how can I provide ControlContainer inside an Angular unit test?

The following is the error produced:

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

My attempt to provide ControlContainer :

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

I have seen other solutions that use:

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

I have had no luck but if there is anyone here who is able to shed some light; I would deeply appreciate it.

I was able to derive the solution from this post:

How to mock ControlContainer in angular unit test?

What I ended up doing was:

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

What I wanted to do was attach the initialized parent form group to the child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM