【问题标题】:Jest test: Pass nested object to react component笑话测试:将嵌套对象传递给反应组件
【发布时间】:2021-07-11 13:21:51
【问题描述】:

我有一个这样的功能组件:

const ImageScreen = (props: any) => {
  const images: object[] = [];
  props.navigation.state.params.images.forEach((image: any) =>
    //some code
  );

  return (
    <View style={CommonStyles.normalPage}>
      // some code
    </View>
  );
};

然后我写Jest来测试这个组件:

test(`renders correctly`, () => {
  const props = {
    navigation: {
      state: {
        params: {
          images: [
            { url: "../sample-images/sample1.jpg" },
            { url: "../sample-images/sample2.jpg" },
          ],
          index: 1,
        },
      },
    },
  };

  const component = renderer.create(<ImageScreen props={props} />);
  let tree = component.toJSON();
  expect(tree).toMatchSnapshot();
});

但我总是报错:TypeError: Cannot read property 'state' of undefined

我对 Jest 和 React Native 都是新手,所以不确定我是否做错了

【问题讨论】:

    标签: javascript reactjs react-native jestjs


    【解决方案1】:

    您已将一个名为“props”的道具传递到组件中。这可以作为组件函数中的属性“props”访问。

    您想要做的是将所有(嵌套的)道具添加到组件中,而不是一个名为“道具”的道具。

    请尝试以下方法:

    const component = renderer.create(<ImageScreen {...props} />);
    

    【讨论】:

    • 我按照你的建议做了,但这次 Jest 给出了错误:“TypeError: success is not a function....getSize: jest.fn((uri, success) => process.nextTick( () => 成功(320, 240))),"
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 2018-06-17
    • 2018-03-23
    • 2021-06-02
    • 1970-01-01
    • 2018-10-19
    • 2021-07-12
    相关资源
    最近更新 更多