首页 > 解决方案 > 如何在不使用 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 的情况下做到这一点。

标签: angulartypescriptunit-testingkarma-jasminespy

解决方案


.spec.ts文件中,声明模拟对象,如:

let formGroupMock: FormGroup;
let formBuilderMock: any;

初始化对象并模拟FormBuildergroup()方法调用,如:

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
    }
});

推荐阅读