【发布时间】:2020-03-28 09:15:54
【问题描述】:
我有一个组件,我已将其属性之一声明为groupForm : FormGroup。在其中一种方法中,我获取表单字段的值并将其分配给一个常量,例如:
const value = this.groupForm.get('field').value;
稍后我使用这个常量来检查一个条件并执行以下操作:
if (value.$type === 'Variable') {
// do something
}
在组件的 .spec.ts 文件中,我正在使用 Jasmin 和 Karma 编写单元测试用例,我试图模拟如下:
let groupFormMock = spyOn(component.groupForm, 'get')
groupFormMock.and.returnValues({
value: {
$type: "Variable",
name: "Variable",
variableType: "Text",
description: "Variable",
category: "Actions",
subCategory: "Variable",
initialValue: "Test",
sortOrder: 0
}
})
但我收到此错误:
Argument of type '{ value: { $type: string; name: string; variableType: string; description: string; category: string; subCategory: string; initialValue: string; sortOrder: number; }; }' is not assignable to parameter of type 'AbstractControl'.
Type '{ value: { $type: string; name: string; variableType: string; description: string; category: string; subCategory: string; initialValue: string; sortOrder: number; }; }' is missing the following properties from type 'AbstractControl': validator, asyncValidator, _parent, _asyncValidationSubscription, and 43 more.
所以,我想,安慰JSON.stringify(this.groupForm.get('variableName')) 的值并将其作为模拟对象返回可以解决问题,但这给了我另一个错误:
An error occurred: Converting circular structure to JSON
--> starting at object with constructor 'Subscriber'
| property '_subscriptions' -> object with constructor 'Array'
| index 0 -> object with constructor 'SubjectSubscription'
--- property '_parentOrParents' closes the circle
get 方法返回的对象,是一个循环对象(对象引用自己),不能被安慰。因此,我需要创建一个 AbstractControl 的模拟对象,以便我可以使用它并在模拟方法中返回它。或者,欢迎任何解决此问题的解决方案。
我被卡住了,任何线索都会有所帮助。
附: : 我需要在不使用 TestBeds 的情况下做到这一点。
【问题讨论】:
-
使用
FormBuilder实例化FormGroup并返回它怎么样? -
好的,会尝试并通知您。
-
谢谢,@Eldar。您的解决方案给出了一个想法。我创建了一个反对的
formGroupMock的FormGroup,修补了formGroupMock.patchValues()之类的值并且它起作用了。 -
你想把它作为答案发布,我可以接受吗?
-
不需要,很乐意提供帮助。
标签: angular typescript unit-testing karma-jasmine spy