How to test that the renderItem function returns a <ListItem />?
renderItem()
returns a JSX element. JSX compiles to React.createElement() which returns an object.
Therefore, the return value from renderItem()
is just an object.
You can test that renderItem()
creates the correct object by doing the following:
it("should display the order as a <ListItem />", () => {
const element = wrapper
.instance()
.renderItem(item);
expect(element.type).toBe(ListItem);
expect(element.props).toEqual({
title: 'Chris Jackson',
subtitle: 'Vice Chairman',
leftAvatar: {
source: { uri: 'https://s3.amazonaws.com/uifaces/faces/twitter/adhamdannaway/128.jpg' },
title: 'C'
}
});
});
You can test FlatList
with react-native-testing-library
Here's example:
Components:
const Item = ({ name ) => <Text>{name}</Text>
class LisItem extends React.Component {
_keyExtractor = (item: { id: string }) => item.id
render() {
return (
<View style={styles.container}>
{todos && (
<FlatList
data={this.props.todos}
keyExtractor={this._keyExtractor}
renderItem={({ item: { id, name } }) => (
<Item
key={id}
name={name}
/>
)}
/>
)}
</View>
)
}
}
Unit testing:
import { render } from 'react-native-testing-library'
const mockDataTodos = [
{
id: 'id-1',
name: 'Todo-1',
},
{
id: 'id-2',
name: 'Todo-2',
},
{
id: 'id-3',
name: 'Todo-3',
},
]
describe('Testing FlatList', () => {
test('Error component should be render when error is true', () => {
const componentTree = render(
<ListItem todos={mockDataTodos} />,
)
expect(componentTree.getAllByType(FlatList).length).toBe(1)
expect(componentTree.getAllByType(Item).length).toBe(mockDataTodos.length)
})
})
Hope this help!