Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test ReactNative Listview item with enzyme

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 } />)
    }      
}
like image 413
Tom Avatar asked Oct 18 '22 09:10

Tom


1 Answers

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);
like image 62
Tom Avatar answered Oct 21 '22 03:10

Tom