【问题标题】:TypeError: Cannot read properties of undefined (reading 'split')"TypeError:无法读取未定义的属性(读取“拆分”)“
【发布时间】:2021-11-10 20:07:59
【问题描述】:

如何使用 Angular 执行“拆分”测试?

我正在尝试对具有“拆分”的方法运行测试,但最终出现此错误

按照下面的方法,测试类spec.ts

  getCellData(row: any, column: any): any {
    const nestedProperties: string[] = column.property.split('.');
    let value: any = row;
    for (const prop of nestedProperties) {
      value = value[prop];
    }
    return value;
  }
 fdescribe('getCellData:', () => {
      const column: any = [{
        property: 'address.street',
        label: 'Rua',
        type: 'boolean',
      }];

      const columnItem: any =[{
        name: 'teste',
        address:{
          street: 'Rua dos Alfeneiros, nº 4'
        }
      }]
     
      let value: any = columnItem;
    
      it('teste A', () => {
        const nestedProperties: string[] = column.property.split('.');
        expect(component.getCellData(column, value)).toEqual(nestedProperties);

      });
    });

【问题讨论】:

  • 为什么在实现和测试中重复const nestedProperties: string[] = column.property.split('.');这行?为什么将所有内容都输入为any?无论如何,这实际上并不是您要测试的结果,因为它会进一步处理它。另请注意,您将column 传递给row 参数,将value 传递给column 参数,这似乎不一致。最后value 是一个数组,它没有property 属性到.split

标签: angular typescript unit-testing karma-jasmine


【解决方案1】:

您传递给 getCellData 的对象是一个对象数组,因此如果您想读取数组中某个元素的属性值,您必须正确索引该数组:

const nestedProperties: string[] = column[0].property.split('.');

但是,您似乎混淆了函数调用中的参数顺序。我想你的意思是这样调用函数:

component.getCellData(value, column)

【讨论】:

  • 感谢您的回答。
猜你喜欢
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 2023-03-24
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
相关资源
最近更新 更多