在Angular的单元测试中,错误“表单控件'phoneNumber'没有值访问器”通常是因为在测试中访问了不存在的表单控件或者未正确初始化的表单控件。
以下是解决这个错误的一些常见方法:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule],
declarations: [YourComponent],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(YourComponent);
component = fixture.componentInstance;
// 初始化表单控件
component.form = new FormGroup({
phoneNumber: new FormControl('') // 初始化phoneNumber控件为空值
});
fixture.detectChanges();
});
it('should have phoneNumber control', () => {
const phoneNumberControl = component.form.get('phoneNumber');
expect(phoneNumberControl).not.toBeNull();
});
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [YourComponent],
}).compileComponents();
}));
通过上述方法中的一种或多种,您应该能够解决“表单控件'phoneNumber'没有值访问器”错误,并且能够成功进行Angular单元测试。