Karma提示需传入FormGroup实例,测试组件时如何给@Input()传值?
我之前也踩过这个坑!咱们直接来搞定它——核心就是在调用fixture.detectChanges()之前,给组件的@Input() form属性赋值一个合法的FormGroup实例,同时要正确使用FormBuilder来创建这个实例,避免"group is not defined"的错误。
步骤1:导入必要的模块和类
首先确保你的测试文件顶部导入了ReactiveForms相关的依赖:
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule, FormBuilder, FormGroup } from '@angular/forms'; // 导入你的待测试组件 import { YourComponent } from './your.component';
步骤2:在测试环境中注入FormBuilder并创建表单实例
在beforeEach块里,先配置TestBed,注入FormBuilder,然后用它来创建你需要的FormGroup。注意要在创建组件实例后、调用detectChanges()前给组件的form输入属性赋值:
describe('YourComponent', () => { let component: YourComponent; let fixture: ComponentFixture<YourComponent>; let fb: FormBuilder; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ReactiveFormsModule], // 必须导入这个才能使用FormBuilder declarations: [YourComponent], providers: [FormBuilder] // 注入FormBuilder服务 }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(YourComponent); component = fixture.componentInstance; fb = TestBed.inject(FormBuilder); // 获取FormBuilder实例 // 用FormBuilder创建你的预制表单 const testForm: FormGroup = fb.group({ // 这里根据组件需要的表单控件来定义,比如: username: [''], email: [''] }); // 给组件的@Input() form赋值 component.form = testForm; // 现在再调用detectChanges(),就不会报错了! fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
为什么这么做?
"Karma formGroup expects a FormGroup instance. Please pass one in" 这个错误的根源是,组件初始化时(也就是第一次调用
detectChanges()时),它的@Input() form属性是undefined,而模板里肯定用了[formGroup]="form"这样的绑定,所以Angular找不到合法的FormGroup实例就报错了。
而"group is not defined"的问题,通常是因为你没有正确实例化FormGroup——要么没导入FormBuilder/ReactiveFormsModule,要么没通过fb.group()创建实例就直接用了。
另一种赋值方式:通过组件的inputs属性
如果你习惯在创建组件时就传入输入属性,也可以这样写:
const testForm = fb.group({ /* 控件定义 */ }); fixture = TestBed.createComponent(YourComponent); // 这里通过componentInstance赋值和上面效果一样 fixture.componentInstance.form = testForm; // 或者用fixture的debugElement来设置: // fixture.debugElement.componentInstance.form = testForm; fixture.detectChanges();
只要确保在detectChanges()之前把合法的FormGroup实例传给组件的@Input() form,问题就能解决啦!
内容的提问来源于stack exchange,提问作者FussinHussin

