unit testing angular component with input.require

781 Views Asked by At

When my components are like this

export OldComponent {
    @input required!: string;
}

I can prepare the unit tests like this:

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

Now that we have input signals (Angular 17)

export NewComponent {
    required = 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.required.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')

2

There are 2 best solutions below

6
Adrian Kokot On BEST ANSWER

To set inputs, you can use ComponentRef<T>.setInput method, which also works with signals:

fixture = TestBed.createComponent(NewComponent);
component = fixture.componentInstance;
fixture.componentRef.setInput('required', 'test');
fixture.detectChanges();
0
Simon Dragsbæk On

If you by any chance use the preview feature Zoneless it can be achieved like so:

fixture = TestBed.createComponent(PostComponent);
component = fixture.componentInstance;
component.id = input('test');

await fixture.whenStable();