gpt4 book ai didi

reactjs - 如何用 enzyme 测试ReactNative Listview项目

转载 作者:行者123 更新时间:2023-12-03 13:37:20 24 4
gpt4 key购买 nike

我正在使用 enzyme 来测试我的组件渲染。

测试 ListView 项目的常用方法是什么?例如,在下面的示例中测试当单击某个项目时,它会触发传递 id 的 onSelect 属性?

我目前正在使用 react-native-mock 这意味着 ListView 不会渲染任何内容,并且我无法将项目分离到单独的组件中,因为它需要来自父级的 onSelect 属性。

export default class extends React.Component {
constructor(props) {
super(props);
this.dataSource = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
})
}
renderItem = ({id, title}) => {
const {onSelect} = this.props;
return <Button onPress={() => onSelect(id)}>{title}</Button>;
}
render() {
const dataSource = this.dataSource.cloneWithRows(this.props.items);
return (
<ListView dataSource={dataSource}
renderRow={this.renderItem } />)
}
}

最佳答案

我使用

完成了这项工作
const wrapper = shallow(<Settings onSelect={onSelectSpy}  />);
const item = shallow(wrapper.instance().renderItem(itemProps));

我发现我最初的尝试虽然看起来有效,但实际上并没有达到我的预期。我现在已将列表本身和项目拆分为单独的组件。

对于我的问题中的最小示例。

export default class extends React.Component {
constructor(props) {
super(props);
this.dataSource = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
})
}
renderItem = (rowProps) => {
const {onSelect} = this.props;
return <ListViewItem {...rowProps} onSelect={onSelect} />
}
render() {
const dataSource = this.dataSource.cloneWithRows(this.props.items);
return (
<ListView dataSource={dataSource}
renderRow={this.renderItem } />)
}
}

以及 ListView 项

//ListViewItem
export default ({id, title, onSelect}) =>
(<Button onPress={() => onSelect(id)}>{title}</Button);

关于reactjs - 如何用 enzyme 测试ReactNative Listview项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37324329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com