这个问题通常出现在使用 Angular 测试模拟组件时,可能是因为对未定义的控件进行了访问,导致该错误出现。为了解决这个问题,你可以在对组件进行模拟时,手动创建 FormGroup 和 FormControl,并将它们传递给被测试组件。
下面是一个代码示例,展示了如何创建 FormGroup 和 FormControl,并将它们传递给被测试组件。
@Component({ selector: 'app-test', template: '' }) class TestComponent { @Input() form: FormGroup; }
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture
beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ TestComponent ] }) .compileComponents(); });
beforeEach(() => { fixture = TestBed.createComponent(TestComponent); component = fixture.componentInstance; component.form = new FormGroup({ control: new FormControl('') }); fixture.detectChanges(); });
it('should create', () => { expect(component).toBeTruthy(); }); });
在这个示例中,我们先创建了一个 TestComponent 组件,并将 FormGroup 和 FormControl 分别命名为 form 和 control。然后,在测试代码中,我们手动创建了 FormGroup 和 FormControl,并将 FormGroup 传递给被测试组件的 form 属性。这样,即使没有通过父组件创建控件,测试仍能通过手动创建控件来运行。