React Native 测试库:滚动 FlatList 到底部

3

我有一个 react-native FlatList 组件,使用了 onEndReached 事件来加载更多项。

我正在使用 react-native-testing-library 测试此组件。测试如下:

  • 组件已挂载。
  • mockedBackend 请求10个项目。
  • 期望 FlatList 渲染这10个项目。
  • 通过触发 fireEvent onEndReached 来请求带有更多项目的下一页。
  • 期望 FlatList 渲染新项目。

测试失败,因为即使更新了 FlatList's data 属性(我根据需要使用了 actwaitFor),FlatList 仍未渲染新项目。

经过一些尝试后,我设法让测试通过,当我将 onScroll 事件滚动到底部并使用硬编码值。

有没有一种方法可以创建一个帮助器来滚动到底部,并考虑到适当的FlatList大小呢?

需要改进的帮助器:

export const scrollListToBottom = (list: ReactTestInstance) => {
  // FIXME: improve to get real list size
  // After some tries these hardcoded values allowed to pass the test
  act(() => {
    fireEvent.scroll(list, {
      nativeEvent: {
        contentSize: {height: 500, width: 100},
        contentOffset: {y: 400, x: 0},
        layoutMeasurement: {height: 100, width: 100},
      }
    })
  })

  // FIXME: if onScroll works perfectly is this even needed?
  act(() => {
    fireEvent(list, 'onEndReached')
  })
}

谢谢。
1个回答

1
import { act, fireEvent } from '@testing-library/react-native';

export const scrollListToBottom = async (list) => {
  // Find the scrollable view within the FlatList
  const scrollableView = list.findByProps({ testID: 'flatlist-scrollable' });

  // Get the height of the content within the FlatList
  const contentHeight = scrollableView.props.contentSize.height;

  // Calculate the scroll position to reach the bottom
  const scrollPosition = {
    x: 0, // Horizontal scroll position
    y: contentHeight, // Scroll to the calculated content height
  };

  // Scroll to the calculated position
  await act(async () => {
    fireEvent.scroll(scrollableView, { contentOffset: scrollPosition });
  });

  // Trigger the onEndReached event
  await act(async () => {
    fireEvent(list, 'onEndReached');
  });
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接