【问题标题】:React Native with Jest - cannot read property <propName> of undefined用 Jest 反应本机 - 无法读取未定义的属性 <propName>
【发布时间】:2019-03-21 17:25:13
【问题描述】:

我正在使用 Jest 和 React Test Renderer 来测试一个 React Native 组件,在该组件中,我在挂载时向 react-navigation 对象添加了一些参数,如下所示:

  componentDidMount() {
    const { setParams } = this.props.navigation;

    setParams({ subTitle: this.props.user.outlet.name.toUpperCase() });
  }

这在 UI 中运行良好,但在测试中我收到错误 TypeError: Cannot read property 'outlet' of undefined

navigation 作为道具传递可以正常工作,但我认为我没有正确传递user。我做错了什么?

这是我的测试(我认为不相关的任何内容都省略了):

const props = {
  navigation: {
    navigate: jest.fn()
  },
  user: {
    // user info here
  }
};

const tree = renderer.create(
    <MockApp mocks={{ ...baseMocks, ...mocks }}>
      <Home {...props} />
    </MockApp>
  );

await wait(0);

expect(tree.toJSON()).toMatchSnapshot();

【问题讨论】:

  • 嗯...我得到TypeError: setParams is not a function 因为navigation 模拟不包括setParams

标签: reactjs react-native jestjs


【解决方案1】:

更新:

也许不是一个完美的解决方案,但考虑到我一开始不明白为什么会失败,我通过检查组件中是否存在 user 使测试通过:

user &&
  user.outlet &&
  navigation.setParams({ subTitle: user.outlet.name.toUpperCase() });

希望有人能解释一下为什么这首先不起作用...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-11
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多