【问题标题】:React App - cannot read prop of children (getting undefined) while testing using Jest and EnzymeReact App - 在使用 Jest 和 Enzyme 进行测试时无法读取孩子的道具(变得未定义)
【发布时间】:2020-02-23 21:54:19
【问题描述】:

我正在尝试使用 Jest 和 Enzyme 对 React 应用程序进行第一次测试。我有一个组件 SignUpForm,它接收子节点并根据其当前状态值呈现正确的子节点。

例子:

if (children.length < currentStep) {
      return <Success />;
    }

一切正常,除非我尝试对其进行测试。这是因为我指向儿童道具并说:

TypeError: 无法读取未定义的属性“长度”

这就是我现在在测试中所做的:

it("Should render without crashing", () => {
    const component = shallow(<SignUpForm />);
    console.log(component);
  });

【问题讨论】:

  • 显然children是未定义的,你在哪里定义的?

标签: javascript reactjs unit-testing jestjs enzyme


【解决方案1】:

您想测试根本没有孩子或未定义的场景,这很好。您需要做的就是再添加一项检查children 变量是否存在:)

if (!children || children.length < currentStep) {
      return <Success />;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 2019-12-24
    • 2018-08-31
    • 2019-03-12
    • 2017-11-09
    • 1970-01-01
    相关资源
    最近更新 更多