angular - 如何在不使用 TestBeds 的情况下模拟 FormGroup 的 get 方法?
问题描述
我有一个组件,我已将其属性之一声明为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 的模拟对象,这样我就可以使用它并在模拟方法中返回它。或者,欢迎任何解决此问题的解决方案。
我被卡住了,任何线索都会有所帮助。
PS:我需要在不使用 TestBeds 的情况下做到这一点。
解决方案
在.spec.ts文件中,声明模拟对象,如:
let formGroupMock: FormGroup;
let formBuilderMock: any;
初始化对象并模拟FormBuilder
的group()
方法调用,如:
formGroupMock = new FormGroup({
field : new FormControl()
});
formBuilderMock = jasmine.createSpyObj('FormBuilder', ['group']);
formBuilderMock.group.and.returnValue(formGroupMock);
将值修补到表单中,例如:
formGroup.patchValue({
field : {
$type: "Variable",
name: "Variable",
variableType: "Text",
description: "Variable",
category: "Actions",
subCategory: "Variable",
initialValue: "Test",
sortOrder: 0
}
});
推荐阅读
- angular - NbAuthService:没有以“电子邮件”名称注册的身份验证策略 - Nebular Firebase 身份验证
- laravel - Laravel 自定义规则的自定义验证错误信息
- vue.js - 无论如何可以从 v-for 循环中的孩子访问 key 属性?Vue
- sql - 根据 ID 和日期识别新数据
- android - 反应本机即时电话不起作用
- setinterval - 是否可以在应用程序中有条件地清除 setInterval?
- json - POST 无法通过 curl 处理 json 请求
- c# - 从 PageFactory 获取使用值
- angular - AG-Grid gridReady 未在使用 Angular 和 Jest 的测试中调用
- ios - 为什么我不能在我的 SwiftUI 代码中使用函数调用填充数组?