5

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 } />)
    }      
}
4

1 回答 1

3

我得到这个工作使用

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 } />)
    }      
}

和列表视图项

//ListViewItem
export default ({id, title, onSelect}) => 
   (<Button onPress={() => onSelect(id)}>{title}</Button);
于 2016-05-20T09:49:53.143 回答