我正在 ParentComponent 中为此方法编写单元测试:
export class ParentComponent {
@ViewChild('childComponent')
childComponent: ChildComponent;
constructor(
private service: UserService
) {}
createUser() {
const newUser: IUser = {
firstName:
this.childComponent?.formGroup?.get('paymentTerm').value,
lastName:
this.childComponent?.formGroup?.get('paymentFibuCode').value,
years:
this.childComponent?.formGroup?.get('determinationRule').value
};
this.service
.createUser(newUser)
.pipe(take(1))
.subscribe(() => {
});
}
}
基本上我需要从子组件中获取 formGroup,我正在使用 ViewChild 执行此操作。子组件是与 html 共享的组件,包含表单、设置表单的 FormService 和 ts. 我有一些方法的文件。
export class ChildComponent {
formGroup: FormGroup = this.formService.createFormGroup();
constructor(
private formService: FormService,
) {}
}
这就是我的子组件中的内容。
在我的单元测试中,我想设置 formGroup 的值。
it('should create user', () => {
const createUserSpy = spyOn(
service,
'createUser'
).and.returnValue(of(null));
component.childComponent.formGroup.setValue({
firstName: 'John',
lastName: 'Doe',
years: 22
});
const inputData: IUser = {
firstName: 'John',
lastName: 'Doe',
years: 22
};
component.createUser();
expect(createUserSpy).toHaveBeenCalledWith(inputData);
});
我的测试失败,我得到无法读取未定义的属性'formGroup'我确实在 beforeEach 中声明了我的 ChildComponent i 声明。
所以我被困在这里,我不知道如何继续,我也尝试创建一个存根,但在这里我的问题是我必须以某种方式从构造函数中获取 formService,我不知道是怎么回事......很多我的问题。
如果有人可以帮助我,我将不胜感激。谢谢