我正在尝试对我创建的这个方法进行单元测试,该方法是在一系列复选框中的一个复选框发生更改时引发的。我们获取传递的事件,确定值以及复选框是否已选中,然后根据 FormArray 是否包含复选框的值来修改表单数组值。该组件继承了它的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'] 重新创建为 FormArray;
使其不为空提供一些建议吗?
如果我没有很好地解释这一点或者我需要解释更多,请告诉我,我将重新表述我的问题。
最佳答案
在测试之前,我必须重新分配表单
beforeEach(() => {
component.parentForm = new FormGroup({
roles: new FormArray(
[ new FormControl('system_admin'), new FormControl('i_and_e_shop') ])
});
fixture.detectChanges();
});
关于Angular:为单元测试设置 FormArray 的起始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61338900/