【问题标题】:Testing wrapper.props shallow render is undefined测试 wrapper.props 浅渲染未定义
【发布时间】:2019-03-14 18:55:23
【问题描述】:

我想测试以下代码:

<React.Fragment>
    <Connect />
    <FlatList
        data={[
            {key: "pp", title: "Privacy Policy"},
            {key: "tos", title: "Terms of Service"},
        ]}
        renderItem={({item}) => {
            return (
                <View
                    onPress={() => this.handleOnPress(item.key)}
                >
                    <Text>{item.title}</Text>
                </View>
            );
        }}
    />
</React.Fragment>

这些是我的测试:

it("should render a FlatList with 2 items", () => {
        const wrapper = shallow(
            <Menu
            />
        );
        expect(wrapper).toMatchSnapshot();
        expect(wrapper.props().data).toHaveLength(2);
    });

由于某种原因,它失败并且显示.data 是未定义的。我基本上想测试我的平面列表有 2 个项目。

【问题讨论】:

    标签: reactjs react-native chai enzyme


    【解决方案1】:

    如果我理解这个问题,那么看起来您正在尝试获取 &lt;Menu/&gt; (wrapper) 的 .props(),而不是包装器的子 &lt;FlatList/&gt;

    通过使用.childAt 方法,您应该能够通过以下方式解决问题:

    it("should render a FlatList with 2 items", () => {
        const wrapper = shallow(
            <Menu
            />
        );
        expect(wrapper).toMatchSnapshot();
    
        // expect(wrapper.props().data).toHaveLength(2);
    
        expect(
          wrapper // the wrapper of 'Menu'
          .childAt(1) // the second child of the 'Menu' which is the 'FlatList'
          .props() // the props of 'FlatList'
          .data // the data field of 'FlatList' props
        ).toHaveLength(2);
    });
    

    Here is more information on the .childAt() method - 希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 2020-08-26
      • 1970-01-01
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2020-12-07
      • 2015-12-01
      相关资源
      最近更新 更多