如何使用玩笑和酵素测试此陈述

在我们的代码中,我有两个语句

const { column, showTooltip, tooltipValue, data } = props;
const key = column.bindProperties[0].properties[0].name;

在测试中,这给出了错误 “ TypeError:无法读取未定义的属性'0'。”

“ column.bindProperties [0] .properties [0] .name;”的含义是什么?以及如何测试。

评论
  • 32场
    32场 回复

    在JS中,您不能保证对象具有某些属性。

    When you try to access column.bindProperties[0].properties[0].name, either column.bindProperties or column.bindProperties[0].properties is undefined - hence the error you're getting.

    You can either use lodash's _.get() or validate the keys are defined using the redundantly annoying:

    const key = column
      && column.bindProperties
      && column.bindProperties[0]
      && column.bindProperties[0].properties
      && column.bindProperties[0].properties[0]
      && column.bindProperties[0].properties[0].name;
    

    This will make sure your code won't break. If one expression in the chain isn't defined, the expression will stop evaluating and you'll just get undefined as the result.