Angular Unit Test for passing FormGroup as @Input
Asked Answered
G

1

13

I want to do a few unit tests there is a formGroup passing as input from parent component to a child component, how to do it.

app.componet.ts

        import { Component, Input } from '@angular/core';
        import { FormGroup, FormControl } from '@angular/forms';
        import { TranslateHelper } from '@app/core/translation';
        
        @Component({
            selector: 'basic-info',
            templateUrl: './'basic.component.html',
            styleUrls: ['./basic.component.scss']
        })
        export class BasicInfoComponent {
            @Input() form: FormGroup;
        
            constructor(private translation: TranslateHelper) {
        
            }
        
            get w(): FormControl {
                return this.form.get('y') as FormControl;
            }
        
            get x(): FormControl {
                return this.form.get('x') as FormControl;
            }
        
            get y(): FormControl {
                return this.form.get('y') as FormControl;
            }
        
            get z(): FormControl {
                return this.form.get('z') as FormControl;
            }
        
        }

app.component.spec.ts

       import { async, ComponentFixture, TestBed } from '@angular/core/testing';
       import { TranslateModule } from '@ngx-translate/core';
            
       import { BasicInfoComponent } from './kyc.component';
       import { FormGroup, FormsModule, ReactiveFormsModule, FormControl, FormBuilder } from '@angular/forms';
       import { TranslateHelper } from '@app/core/translation';
            
            describe('BasicInfoComponent', () => {
                let component: BasicInfoComponent;
                let fixture: ComponentFixture<BasicInfoComponent>;
                const fb = jasmine.createSpyObj('FormBuilder', ['group']);
                const formGroup = new FormGroup(
                    { identityVerificationDocumentTypeId: new FormControl('sfs'), addressVerificationDocumentTypeId: new FormControl('test!') });
                (<jasmine.Spy>(fb.group)).and.returnValue(formGroup);
            
                beforeEach(async(() => {
                    TestBed.configureTestingModule({
                        imports: [
                            ReactiveFormsModule,
                            FormsModule,
                            TranslateModule.forRoot()
                        ],
                        providers: [
                            TranslateHelper,
                            { provide: FormBuilder, useValue: fb }
                        ],
                        declarations: [BasicInfoComponent]
                    })
                        .compileComponents();
                }));
            
                beforeEach(() => {
                    fixture = TestBed.createComponent(BasicInfoComponent);
                    component = fixture.componentInstance;
                    fixture.detectChanges();
                });
            
                it('should create', () => {
                    expect(component).toBeTruthy();
                });
            
                describe('control getters', () => {
                    it('should return x control', () => {
                        const control = component.form.controls['x'];
                        expect(control).toBeTruthy();
                    });
            
                    it('should return y control', () => {
                        const control = component.form.controls['y'];
                        expect(control).toBeTruthy();
                    });
                });
            
            });

Error

Error: formGroup expects a FormGroup instance. Please pass one in.

       Example:

       
    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });
Error: formGroup expects a FormGroup instance. Please pass one in.

       Example:

       
    <div [formGroup]="myGroup">
      <input formControlName="firstName">
    </div>

    In your class:

    this.myGroup = new FormGroup({
       firstName: new FormControl()
    });
Gandzha answered 29/7, 2020 at 11:37 Comment(1)
BasicInfoComponent requires form property to be defined in order to work properly. Where did you set it? Mocking FormBuilder does nothing in your caseHuntsman
C
15

You need to create a formGroup instance.

In your spec file (app.component.spec.ts) add the following on beforeEach

  beforeEach(() => {
    fixture = TestBed.createComponent(BasicInfoComponent);
    component = fixture.componentInstance;
    // The component expect an input called `form`. You have to supply it in the test
    component.form = new FormGroup({
      x: new FormControl('', Validators.required),
      y: new FormControl('', Validators.required),
      z: new FormControl('', Validators.required),
    });
    fixture.detectChanges();
  });
Candycecandystriped answered 29/7, 2020 at 11:57 Comment(5)
That is my Input controller, this.fb.group({ w: ['', Validators.required], xy: ['', Validators.required], y: ['', Validators.required], z: ['', Validators.required], }); What should i place in inside componet.formGandzha
@ZahidRahman Here is your component export class BasicInfoComponent { @Input() form: FormGroup; You have to setup component.formHuntsman
@ZahidRahman I have added the snippet you need to setup component.formCandycecandystriped
@AhmadAlfy It shows error Type '(string | ((control: AbstractControl) => ValidationErrors))[]' is missing the following properties from type 'AbstractControl': validator, asyncValidator, _parent, _asyncValidationSubscription, and 44 morGandzha
@ZahidRahman you need to add the form controls. I have updated the answerCandycecandystriped

© 2022 - 2024 — McMap. All rights reserved.