React Native Testing Framework findBy doesn't find and waitFor doesn't wait

642 Views Asked by At

This is an image gallery and I'm confident it's working correctly. It runs fine in the simulator. I've tried to variations of the same test:

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

and

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

In both instances the test fails with: Unable to find node on an unmounted component.

Inside my tsx file I have a useEffect hook that preloads all the images before displaying them. It then updates state (which causes another unrelated issue)

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

Then in the return:

// 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>
  );

Like I said, the code is working fine in the simulator and takes way less than 4.5 seconds to load. Suggestions?

1

There are 1 best solutions below

0
On

For anyone who finds this in the future... The issue was with: Image.prefetch(image.url);

Even though I was testing with inline data (as opposed to images hosted on a web server) Jest still had issues solving this. I fixed it by mocking Image.prefetch.