gpt4 book ai didi

react-native - 如何测试renderItem函数返回

转载 作者:行者123 更新时间:2023-12-04 04:57:40 27 4
gpt4 key购买 nike

我正在使用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 />

最佳答案

您可以使用react-native-testing-library测试FlatList
例子如下:

组件:

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


单元测试:
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)
})
})

希望对您有所帮助!

关于react-native - 如何测试renderItem函数返回<ListItem/>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52017521/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com