首页 > 解决方案 > 编写单元测试用例时无法将 undefined 或 null 转换为对象

问题描述

当我尝试为该函数运行单元测试时,我收到错误“无法将未定义或 null 转换为对象”

请指导我哪里出错了。

这是 ts 文件中的函数-

filterTargetWeightingFactor(data: any) {
    const filterTargetWeight: any = [];
    Object.keys(data).forEach(function(key) {
      filterTargetWeight.push(key);
    });
    return filterTargetWeight.sort();
  }

以下是该功能的规范文件中的代码 -

it('should return sorted data', () => {
    const unsortedData = {
      'b':'abc',
      'c':'vgf',
      'a':'sdf'
    }
    let sortedData = [ ];
    Object.keys({'key': 'value'})
    let finalArr = component.filterTargetWeightingFactor(unsortedData);
    expect(finalArr).toBe(['a','b','c']);
  });

标签: angularunit-testing

解决方案


推荐阅读