Search code examples
angularnested-forms

Testing child element in nested driven template form


I need to have nested template driven form and I used this guide to do it : Angular: Nested template driven form

Unfortunately as the first comment in the article is saying, when I tried to test my component I uncounterd this error :

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

It seems that since the child component need to use the existing ngForm from is parent it can't be tested on is own.

This stackblitz is showing what i'm trying to say. The AddressComponent is the child and AppComponent the parent.

Any help will be appreciated.


Solution

  • Since your AddressComponent requires an existing NgForm, you need to provide it as part of your test setup:

    TestBed.configureTestingModule({
       imports: [FormsModule],
       declarations: [AppComponent, AddressComponent, HelloComponent],
       providers: [
         { provide: NgForm, useValue: new NgForm([], []) }
       ]
    });
    

    This resolves the error, but I have never done this before. I can make not comment on the downstream impacts of this. Long-term, you may want to implement your own MockNgForm class and then use an instance of that instead.