使用react-native-testing-library测试时FlatList的testID无法找到
尝试对FlatList做单元测试,验证滚动一定距离后某个视图弹出,但测试时找不到FlatList设置的testID="LIST_OF_TRANSACTIONS",渲染树中只有renderItem生成的子项带有随机testID(如test-list-undefined),找不到父容器的目标testID。
相关代码
FlatList组件
<FlatList testID={LIST_OF_TRANSACTIONS} ref={flatlistRef} bounces onScroll={scrollEventHandler} data={dateListOfTransactions} showsVerticalScrollIndicator={false} scrollEventThrottle={16} onContentSizeChange={handleContentSizeChange} contentContainerStyle={{ paddingTop: maxHeaderHeight, paddingHorizontal: 30, paddingBottom: paddingToBeAdded, }} renderItem={renderItem} />
LIST_OF_TRANSACTIONS = "LIST_OF_TRANSACTIONS"
测试用例
it("The scroll up button should be visible when the flatlist is scrolled", async () => { const { getByTestId, queryByTestId } = render(<GetWrappedComponent />); fireEvent.scroll(getByTestId(LIST_OF_TRANSACTIONS), { nativeEvent: { contentSize: { height: 600, width: 400 }, contentOffset: { y: 200, x: 0 }, layoutMeasurement: { height: 400, width: 600 }, }, }); await waitFor(() => { getByTestId(SCROLL_UP_INDICATOR); }); expect(getByTestId(SCROLL_UP_INDICATOR)).toBeOnTheScreen(); });
包裹组件结构
<Provider store={store}> <TransactionList/> </Provider>
报错信息
Unable to find an element with testID: LIST_OF_TRANSACTIONS
1. 确认FlatList是否实际渲染
如果dateListOfTransactions为空数组,FlatList不会渲染主容器,只会显示空状态(若设置了ListEmptyComponent)或直接不渲染。测试时要确保store中初始化了足够的dateListOfTransactions数据,让FlatList正常渲染出列表容器。
2. 改用screen查询并等待组件渲染
React Native Testing Library推荐使用screen对象查询元素,配合waitFor确保FlatList完成渲染:
import { screen, waitFor } from '@testing-library/react-native'; it("The scroll up button should be visible when the flatlist is scrolled", async () => { render(<GetWrappedComponent />); // 等待FlatList渲染完成 const flatList = await waitFor(() => screen.getByTestId(LIST_OF_TRANSACTIONS)); fireEvent.scroll(flatList, { nativeEvent: { contentSize: { height: 600, width: 400 }, contentOffset: { y: 200, x: 0 }, layoutMeasurement: { height: 400, width: 600 }, }, }); await waitFor(() => { expect(screen.getByTestId(SCROLL_UP_INDICATOR)).toBeOnTheScreen(); }); });
3. 检查FlatList的testID传递逻辑
React Native的FlatList在测试环境中,testID可能会被应用到内部的ScrollView上,而非最外层容器。可以尝试结合角色查询:
const flatList = screen.getByRole('scrollview', { name: LIST_OF_TRANSACTIONS });
同时确认没有其他组件占用了同一个testID。
4. 验证store初始化数据
检查GetWrappedComponent中的store是否正确初始化了dateListOfTransactions数据。若数据未加载成功,FlatList不会渲染,自然找不到对应testID。可在测试前手动dispatch动作注入测试数据:
import store from '../path/to/store'; it("The scroll up button should be visible when the flatlist is scrolled", async () => { // 提前注入测试数据 store.dispatch({ type: 'LOAD_TRANSACTIONS', payload: mockTransactions }); render(<GetWrappedComponent />); const flatList = await waitFor(() => screen.getByTestId(LIST_OF_TRANSACTIONS)); // 后续测试逻辑... });
内容的提问来源于stack exchange,提问作者Hardik3296

