【问题标题】:React Native Testing Framework findBy doesn't find and waitFor doesn't waitReact Native 测试框架 findBy 没有找到并且 waitFor 没有等待
【发布时间】:2021-05-13 04:24:05
【问题描述】:

这是一个图片库,我相信它可以正常工作。它在模拟器中运行良好。我尝试过相同测试的变体:

 test('main image should display', async () => {
    const { findByTestId } = render(<ImageGallery images={images} />);
    const mainImage = await findByTestId('largeImage');
    expect(mainImage).toBeDefined();
  });

test('main image should display', async () => {
    const { getByTestId } = render(<ImageGallery images={images} />);
    await waitFor(() => {
      expect(getByTestId('largeImage')).toBeDefined();
    });
  });

在这两种情况下,测试都失败了:无法在未安装的组件上找到节点。

在我的 tsx 文件中,我有一个 useEffect 挂钩,可以在显示之前预加载所有图像。然后它会更新状态(这会导致另一个不相关的问题)

 // Cache all images in the gallery after initial component render
  useEffect(() =>  {
    if (!imagesReady) {
      const loadedImages: Array<Promise<boolean>> = images.map((image) => {
        return Image.prefetch(image.url);
      });

      Promise.all(loadedImages).then((imageLoadStatus) => {
        // Filter out any images that didn't properly load
        images = images.filter((_, index) => imageLoadStatus[index]);
        setActiveImage(images[0]);
        setImagesReady(true);
      });
    }
  });

然后在返回:

// Render either loading indicator or image gallery conditionally.
  if (!imagesReady) {
    return (
      <Container>
        <ActivityIndicator size="small" color="#202020" testID="loading" />
      </Container>
    );
  }

  return (
    
    <Container testID="galleryWrapper">
      <LargeImage source={{ uri: activeImage.url }} testID="largeImage" />
      <ThumbnailList
        horizontal
        data={images}
        renderItem={thumbnail}
        keyExtractor={(image) => image.id}
        showsHorizontalScrollIndicator={false}
      />
    </Container>
  );

就像我说的,代码在模拟器中运行良好,加载时间不到 4.5 秒。有什么建议吗?

【问题讨论】:

    标签: react-native testing jestjs react-native-testing-library


    【解决方案1】:

    对于将来发现此问题的任何人...问题在于: Image.prefetch(image.url);

    即使我使用内联数据(而不是托管在 Web 服务器上的图像)进行测试,Jest 仍然无法解决这个问题。我通过模拟 Image.prefetch 来修复它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 2022-06-20
      • 2020-07-13
      相关资源
      最近更新 更多