测试 wrapper.props 浅渲染未定义

Testing wrapper.props shallow render is undefined

我想测试以下代码:

<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 个项目。

如果我理解这个问题,那么看起来您正在尝试获取 <Menu/> (包装器)的 .props() ,而不是 <FlatList/> child 的包装。

通过使用 .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 - 希望对您有所帮助