Testing ReactiveFormModule in Angular18

Discussão em 'Angular' iniciado por Louis Chamaillard, Outubro 22, 2024.

  1. So I'm working on a lib, on its unit tests currently with this weird error :


    TypeError: Cannot read properties of null (reading 'firstCreatePass')
    ​

    So i invastigated, didn't find anything this useful. I made a test component "input-test" to isolate the error:

    input-test.component.html

    <input type="text" [formControl]="control">

    input-test.component.ts

    import { Component } from '@angular/core';
    import { FormControl, ReactiveFormsModule } from '@angular/forms';

    @Component({
    selector: 'app-input-test',
    standalone: true,
    imports: [ReactiveFormsModule],
    templateUrl: './input-test.component.html',
    styleUrl: './input-test.component.css'
    })
    export class InputTestComponent {

    control: FormControl = new FormControl();
    }


    input-test.component.spec.ts

    import { ComponentFixture, TestBed } from '@angular/core/testing';

    import { InputTestComponent } from './input-test.component';

    describe('InputTestComponent', () => {
    let component: InputTestComponent;
    let fixture: ComponentFixture<InputTestComponent>;

    beforeEach(async () => {
    await TestBed.configureTestingModule({
    // tested both with and without ReactiveFormModules, didn't change anything
    imports: [InputTestComponent, ReactiveFormsModule]
    })
    .compileComponents();

    fixture = TestBed.createComponent(InputTestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    });

    it('should create', () => {
    expect(component).toBeTruthy();
    });
    });


    The error I mentionned at first appears when running npm run test I managed to get rid of it by removing the ReactiveFormsModule, but if i do so i can't bind to FormControl anymore, and I need it.

    Moreover, i found that if I change the template to this :

    input-test.component.html

    <form>
    <input type="text" [formControl]="control">
    </form>


    Then the error becomes


    NG0203: inject() must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with runInInjectionContext. Find more at https://angular.dev/errors/NG0203
    ​

    I'm pretty stuck right now if anyone has an idea it'll really help.

    Continue reading...

Compartilhe esta Página