Testsetup for Form in Angular fails

Discussão em 'Angular' iniciado por BreadcrumbPie, Fevereiro 3, 2025.

  1. I do have an dynamic-form-component which is set up like this:

    export class DynamicformComponent implements OnInit {

    isDropdownOpen = false;

    @Input() questions: Formbase<string>[] | null = [];
    form!: FormGroup;

    @Output() emitFormObj = new EventEmitter<any>();

    get dropdownQuestions() {
    return this.questions?.filter(q => q.controlType === 'dropdown') || [];
    }

    hasDropdownQuestion(): boolean {
    return this.dropdownQuestions.length > 0;
    }

    constructor(private qcs: QuestioncontrolService) {}

    ngOnInit() {
    this.form = this.qcs.toFormGroup(this.questions as Formbase<string>[]);
    } etc.


    and I would like to setup a test for it which I did this way:

    describe('DynamicformComponent', () => {
    let component: DynamicformComponent;
    let fixture: ComponentFixture<DynamicformComponent>;
    let mockQCS: jasmine.SpyObj<QuestioncontrolService>;

    beforeEach(async () => {
    mockQCS = jasmine.createSpyObj('QuestioncontrolService', ['toFormGroup']);
    mockQCS.toFormGroup.and.returnValue(new FormGroup({
    dropdown1: new FormControl('')
    }));

    await TestBed.configureTestingModule({
    declarations: [DynamicformComponent, DynamicformquestionComponent],
    imports: [
    HttpClientTestingModule,
    ReactiveFormsModule],
    providers: [{ provide: QuestioncontrolService, useValue: mockQCS }],
    schemas: [NO_ERRORS_SCHEMA]
    }).compileComponents();

    fixture = TestBed.createComponent(DynamicformComponent);
    component = fixture.componentInstance;

    component.questions = [
    { key: 'dropdown1', label: 'Dropdown', controlType: 'dropdown' } as Formbase<string>
    ];

    component.form = new FormGroup({
    dropdown1: new FormControl('')
    });

    fixture.detectChanges();
    });


    I tried to mock the form but it fails and I'm getting the error:


    NG01052: formGroup expects a FormGroup instance. Please pass one in.
    ​

    I thought this should be quite a working setup - but obviously it isn't. Can anyone give me a hint why the form-mock doesn't work?

    Continue reading...

Compartilhe esta Página