我正在尝试对我创建的此方法进行单元测试,该方法在一系列复选框中的一个复选框更改时引发。我们通过传递的事件,确定该值以及是否已选中该复选框,然后根据FormArray包含还是不包含复选框的值来修改Form Array的值。该组件继承其parentForm,因此我在组件的单元测试中对此进行了模拟。
我的问题是,下面的const checkArray: FormArray
代码在我的单元测试中总是一个空数组。这是方法:
checkboxChange($event: any): void {
const checkArray: FormArray = this.parentForm.controls['roles'] as FormArray;
if ($event.source.value && $event.source.checked) {
checkArray.push(new FormControl($event.source.value));
} else if ($event.source.value && !$event.source.checked) {
checkArray.controls.forEach((item: FormControl, index: number) => {
if (item.value === $event.source.value) {
checkArray.removeAt(index);
return;
}
});
}
}
[好,所以在我的单元测试中,我尝试重新创建表单,在其初始状态下,我将其保留为空,因为我将其用于其他测试。然后,在测试上述代码之前,我尝试设置表单项的值。
beforeEach(() => {
fixture = TestBed.createComponent(RolesCheckboxesComponent);
component = fixture.componentInstance;
component.parentForm = new FormGroup({
roles: new FormArray([])
});
fixture.detectChanges();
});
describe('checkboxChange', () => {
it('should remove a role that is already present then add it again', async(() => {
fixture.whenStable().then(() => {
component.parentForm.controls['roles'].patchValue(
[new FormControl('system_admin'), new FormControl('i_and_e_shop')]
);
// component.parentForm.controls['roles'].value.push(new FormControl('system_admin'));
// component.parentForm.controls['roles'].value.push(new FormControl('i_and_e_shop'));
fixture.detectChanges(component.parentForm.controls['roles'].value);
component.checkboxChange({ source: { value: 'i_and_e_shop', checked: false } });
expect(component.parentForm.controls['roles'].value)
.toEqual(['system_admin']);
component.checkboxChange({ source: { value: 'i_and_e_shop', checked: true } });
expect(component.parentForm.controls['roles'].value).toEqual(['system_admin', 'i_and_e_shop']);
});
}));
});
我的单元测试的问题是,当我的方法测试为component.parentForm.controls['roles']
为空时,在应用程序中将使用FormControls对其进行填充。我曾尝试推送,修补FormArray的值,但我似乎无济于事。谁能给我一些有关如何重新创建this.parentForm.controls['roles'] as FormArray;
的建议,以便它不为空?
如果我不能很好地解释这一点,或者我需要进一步解释,请告诉我,我将重新陈述我的问题。
在测试之前,我不得不重新分配表格
beforeEach(() => {
component.parentForm = new FormGroup({
roles: new FormArray(
[ new FormControl('system_admin'), new FormControl('i_and_e_shop') ])
});
fixture.detectChanges();
});