当我的组件是这样的

export OldComponent {
    @input required!: string;
}

我可以像这样准备单元测试:

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

现在我们有了输入信号(Angular 17)

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

我们如何准备组件以进行测试?这不能编译,因为输入信号是只读的:

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

我试着不把它分配给测试,但显然它抛出了: Error: NG0950: Input is required but no value is available yet. Find more at https://angular.io/errors/NG0950

我不想使用正常的、不需要的输入的解决方法: input<string>('default value')

推荐答案

要设置输入,您可以使用ComponentRef<T>.setInput方法,该方法也适用于信号:

fixture = TestBed.createComponent(NewComponent);
component = fixture.componentInstance;
fixture.componentRef.setInput('required', 'test');
fixture.detectChanges();

Angular相关问答推荐

PrimeNG面包屑组件生成奇怪的&

笔刷Angular 为17

独立组件;依赖项注入

选中/取消选中-复选框未正确返回TRUE或FALSE

NGX- colored颜色 Select 器安装出错

PrimeNg选项卡视图选项卡

使用jsPDF生成带有图像的PDF时出现灰色条纹

如何在AngularJs中剪断细绳

在以下位置升级到Angular 16 Break Sharepoint广告:This._history.replaceState不是函数

从组件调用时服务中的 AddTodo 方法不起作用

Angular APP_INITIALIZER 中的 MSAL 身份验证

PrimeNG:如何以编程方式更改分页器中的选定页面?

异步管道模板中的局部变量(Angular 2+)

CORS 策略和 .NET Core 3.1 的问题

单选按钮的Angular2 Reactive Forms formControl

请求 http.GET 时发送的 Angular2 OPTIONS 方法

如何设置背景 colored颜色 IONIC 4

Angular 4 设置下拉菜单中的选定选项

ng-template 上的 *ngFor 不输出任何内容

如何在 Angular 4 中翻译 mat-paginator?