首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >测试wrapper.props浅层渲染未定义

测试wrapper.props浅层渲染未定义
EN

Stack Overflow用户
提问于 2018-10-10 07:08:11
回答 1查看 828关注 0票数 1

我想测试以下代码:

代码语言:javascript
复制
<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>

以下是我的测试:

代码语言:javascript
复制
it("should render a FlatList with 2 items", () => {
        const wrapper = shallow(
            <Menu
            />
        );
        expect(wrapper).toMatchSnapshot();
        expect(wrapper.props().data).toHaveLength(2);
    });

由于某些原因,它失败了,并且显示.data是未定义的。我主要想测试我的平面列表是否有2个项目。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-10 07:18:45

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

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

代码语言:javascript
复制
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 -希望这能有所帮助

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52730454

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档