angular - 单元测试 FormGroup 无法读取未定义的 Prop 值

尝试在我的组件中编写单元测试,我更新了 FormArray 中的 FormGroup 中的值。但是,在运行测试时出现错误:

Cannot Read Prop value of undefined

运行应用程序,代码编译正常,当用户在 GUI 上触发时,值会更新。错误似乎链接到此行:

_.find(this.myForm.value.settings, {task: 'Set Alarm}).visible = true;

组件:

nominatedArray = [];
myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = this.fb.group({
      title: ['title'],
      settings: fb.array([
        fb.group({
          completed: fb.control(false),
          task: fb.control('Set Alarm'),
          visible: fb.control(false)
        }),
        fb.group({
          completed: fb.control(false),
          task: fb.control('Brush teeth'),
          visible: fb.control(false)
        }),
        fb.group({
          completed: fb.control(false),
          task: fb.control('Shower'),
          visible: fb.control(false)
        })
      ])
    })
  }  

public updateVis() {
   // TEST IS FAILING AT 'VALUE' LINE BELOW
    _.find(this.myForm.value.settings, {task: 'Set Alarm}).visible = true;
}

测试规范:

it('should update value, () => {

    component.myForm = this.fb.group({
      title: ['title'],
      settings: fb.array([
        fb.group({
          completed: fb.control(false),
          task: fb.control('Set Alarm'),
          visible: fb.control(false)
        }),
        fb.group({
          completed: fb.control(false),
          task: fb.control('Brush teeth'),
          visible: fb.control(false)
        }),
        fb.group({
          completed: fb.control(false),
          task: fb.control('Shower'),
          visible: fb.control(false)
        })
      ])
    })

    component.updateVis();

    expect(component.myForm.value.settings[0].visible).toBeFalsy();

});

最佳答案

您可以在下面尝试一下吗:因为我认为您不必初始化表单。创建组件时很简单 component.form 将为您提供。

component.myForm = this.fb.group({ -- 和 this.fb -- 我认为您的规范文件中的 this 行可能有问题。

it('should update value, () => {
    console.log(component.form); // share value if this test case didn't work
    component.updateVis();

    expect(component.myForm.value.settings[0].visible).toBeFalsy();

});

 it('should update value, () => {

        component.updateVis();
        fixture.detectChanges();
    console.log(component.myForm.value); // share this value if solution didn't work
       expect(component.myForm.value.settings[0].visible).toBeFalsy();

    });

https://stackoverflow.com/questions/62322648/

相关文章:

reactjs - 如何在 recharts 中使用 .map 函数创建双轴线图

python - Pandas 仅与列中的非空值合并并保留具有空值的值

r - unnest_longer 给出美元符号而不是正常的 tibble

laravel-5 - 解决facade root has not been set

tensorflow - 物体检测损失不减少,AP增加

node.js - sqlite3 安装在 node 和 macos 上报错

r - 在 R::multipanelfigure 中设置面板标签大小

sql - hive 中的 with (nolock) 相当于 sql (nolock)

amazon-web-services - 亚马逊电子病历 : do i need core nod

python - 如何在 jupyterlab 中更改内核的 Logo 图像