【发布时间】:2020-06-19 09:00:20
【问题描述】:
我在一个 Angular 9 项目中工作。
我有一个组件接受 formBuilder 作为来自父组件的输入。 这是我的子组件(我正在测试的那个):
export class ChildComponent implements OnInit {
@Input() parentForm: FormGroup; //this is coming from the parentComponent
ngOnInit(): void {
if (this.parentForm) {
this.filteredSelectables = this.parentForm
.get("recipientTypes")
...
}
}
...
我想为这个组件编写测试,但是我需要创建一个测试可以使用的表单(或者我需要模拟父组件并返回我想要的表单?)
我已将 FormBuilder 添加到 testBed 提供程序,但我仍然不知道如何制作可以用来测试的模拟表单。 “应该创建”测试正在通过,但我无法测试其他任何东西,因为 parentForm 不能为它们为空。这是我目前的测试:
describe("ChildComponent", () => {
let component: ChildComponent;
let fixture: ComponentFixture<ChildComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ChildComponent, MatAutocomplete],
providers: [FormBuilder],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(ChildComponent);
component = fixture.componentInstance;
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(ChildComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it("should create", () => {
expect(component).toBeTruthy();
});
...
我尝试过这样创建表单:
component.parentForm = FormBuilder.group({
recipientTypes: new FormControl(
{
value: ["mock"],
disabled: true
},
Validators.required
)
});
并将其添加到 beforeEach() 甚至在实际测试中。但我出错了。
我想也许我需要模拟 parentComponent 并让它发送一个 formBuilder? 这是我的父组件:
export class ParentComponent implements OnInit, OnDestroy {
parentForm: FormGroup;
constructor(
private router: Router,
private formBuilder: FormBuilder
) {}
ngOnInit() {
this.setFormTemplate();
}
setFormTemplate() {
this.templateForm = this.formBuilder.group({
name: new FormControl(
{
value: this.name,
disabled: true
},
Validators.required
),
recipientTypes: new FormControl(
{
value: this.recipientTypes,
disabled: true
},
Validators.required
)
});
}
...
如何为我的测试制作一个 formBuilder?
【问题讨论】:
-
你得到什么错误?
-
我得到:
Property 'group' does not exist on type 'typeof FormBuilder,如果我只使用FormBuilder.group。如果我尝试component.formBuilder它不起作用,因为组件实际上没有formBuilder,父组件有。我错了:Property 'formBuilder' does not exist on type 'ChipsAutocompleteInputComponent'.
标签: angular testing angular-reactive-forms formbuilder angular9