我正在使用酶来测试我的组件渲染。
测试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 } />)
}
}
答案 0 :(得分: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);