unit testing angular component with input.required

Discussão em 'Angular' iniciado por Ricardo Aranguren, Março 21, 2025.

  1. When my components are like this

    export OldComponent {
    @input myInput!: string;
    }


    I can prepare the unit tests like this:

    fixture = TestBed.createComponent(OldComponent);
    component = fixture.componentInstance;
    component.myInput = 'test';
    fixture.detectChanges();


    Now that we have input signals (Angular 17)

    export NewComponent {
    myInput = input.required<string>();
    }


    How do we prepare the component for testing? This doesn't compille because an input signal is read-only:

    fixture = TestBed.createComponent(NewComponent);
    component = fixture.componentInstance;
    component.myInput.set('test'); // Does not compile
    fixture.detectChanges();


    I tried not assigning it for the tests, but obviously it throws: Error: NG0950: Input is required but no value is available yet. Find more at https://angular.io/errors/NG0950

    I would not like to use the workaround of using a normal, not required input: input<string>('default value')

    Continue reading...

Compartilhe esta Página