我正在使用React Native构建我的应用程序,并使用Jest和Enzyme进行单元测试。如何测试我的<FlatList />
的renderItem()
函数?
它返回来自React-Native-Elements库的<ListItem />
。
让我给你一个示例代码:
import { ListItem } from 'react-native-elements'
export class MyList extends Component {
const list = [
{
name: 'Amy Farha',
subtitle: 'Vice President'
},
{
name: 'Chris Jackson',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
subtitle: 'Vice Chairman'
},
... // more items
]
keyExtractor = (item, index) => index
renderItem = ({ item }) => (
<ListItem
title={item.name}
subtitle={item.subtitle}
leftAvatar={{
source: item.avatar_url && { uri: item.avatar_url },
title: item.name[0]
}}
/>
)
render () {
return (
<FlatList
keyExtractor={this.keyExtractor}
data={this.state.dataSource}
renderItem={this.renderItem}
/>
)
}
}
我希望能够测试renderItem()
函数。我的问题是,wrapper.instance().renderItem({item: item})
返回错误:TypeError: wrapper.instance(...).renderItem(...).find is not a function
。让我给你我写的测试代码:
describe("component methods", () => {
let wrapper;
let props;
let item;
beforeEach(() => {
props = createTestProps();
wrapper = shallow(<MyList {...props} />);
});
describe("renderItem", () => {
describe("user", () => {
beforeEach(() => {
item = {
name: 'Chris Jackson',
avatar_url: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg',
subtitle: 'Vice Chairman'
};
});
it("should display the order as a <ListItem />", () => {
expect(
wrapper
.instance()
.renderItem(item)
.find("ListItem")
).toHaveLength(1);
});
});
});
});
我该如何编写此测试,以便测试函数是否正确呈现<ListItem />
?