typescript 如何创建与方法返回相同的表单组?

z4bn682m  于 2023-03-19  发布在  TypeScript
关注(0)|答案(1)|浏览(90)

我创建了一个显示在对话框上的表单组。我正在尝试写一些单元测试,以确保方法返回表单组。
单击按钮时调用的方法为:

closeDialogAndSendForm(): void {
    this.dialogWindow.close(this.form)

}
我的单元测试如下所示(我创建了一个表单,其中只有一个字段用于测试用例):

it('should close dialog and return FormGroup', fakeAsync(async () => {
    await selectAnswers();
    let resultFormGroup = createResultFormGroup();
    let spy = spyOn(component.dialogWindow, 'close');
    flush();
    fixture.detectChanges();
    clickOnButton('SUBMIT', fixture);
    expect(spy).toHaveBeenCalledWith(resultFormGroup);
}));

createResultFormGroup()中,我想创建与该方法返回的表单相同的表单:

function createResultFormGroup(): FormGroup {
    let form = new FormGroup({testField: new FormControl(true, Validators.required)});
    return form;
}

但我发现了很多不同之处,比如:

Call 0:
  Expected $[0]._onCollectionChange = Function to equal Function.
  Expected $[0].pristine = false to equal true.
  Expected $[0].controls.testField._pendingDirty = true to equal false.
  Expected $[0].controls.testField._onCollectionChange = Function to equal Function.
  Expected $[0].controls.testField.pristine = false to equal true.
  Expected $[0].controls.testField._onDisabledChange.length = 1 to equal 0.
  Unexpected $[0].controls.testField._onDisabledChange[0] = Function in array.
  Expected $[0].controls.testField._rawValidators = [ Function ] to equal Function.
  Expected $[0].controls.testField._composedValidatorFn = Function to equal Function.
  Expected $[0].controls.testField._onChange.length = 1 to equal 0.
  Unexpected $[0].controls.testField._onChange[0] = Function in array.
  Expected $[0].controls.testField.valueChanges.currentObservers = [  ] to equal null.
  Expected $[0].controls.testField.statusChanges.currentObservers = [  ] to equal null.
  Expected $[0].valueChanges.currentObservers = [  ] to equal null.
  Expected $[0].statusChanges.currentObservers = [  ] to equal null.
Error: Expected spy close to have been called with:

我可以模拟它或我不知道比较只有字段名和值?

i5desfxk

i5desfxk1#

代码看起来在预期的FormGroup和该方法返回的实际FormGroup之间存在一些差异。您可以尝试只比较字段名和值,或者创建一个与预期对象匹配的模拟FormGroup对象。
若要创建模拟FormGroup对象,请尝试使用FormGroup构造函数,该构造函数包含与expectd对象具有相同字段名和初始值的对象。例如:

const expectedFormGroup = new FormGroup({
  testField: new FormControl(true, Validators.required)
});

// Create a mock FormGroup with the same field names and initial values
const mockFormGroup = new FormGroup({
  testField: new FormControl(true, Validators.required)
});

// Compare the mock FormGroup with the actual FormGroup
expect(spy).toHaveBeenCalledWith(mockFormGroup);

这将帮助您测试该方法并使其工作。

相关问题