I am using enzyme to test my component rendering.
What is the usual approach to testing ListView items? For instance, in the following example to test that when an item is clicked, it triggers the onSelect prop passing the id?
I am currently using react-native-mock which means that the ListView does not render anything, and I can't separate the item into a separate component as it needs the onSelect prop from the parent.
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 } />)
}
}
I got this working using
const wrapper = shallow(<Settings onSelect={onSelectSpy} />);
const item = shallow(wrapper.instance().renderItem(itemProps));
I found my initial attempt while seeming to work wasn't actually doing what I had expected. I have now split the list itself and the item into separate components.
So for the minimal example in my question.
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 } />)
}
}
And the listview item
//ListViewItem
export default ({id, title, onSelect}) =>
(<Button onPress={() => onSelect(id)}>{title}</Button);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With