React Native Testing Framework findBy Doesn't Find and waitFor Doesn't Wait

Please provide the following:

  1. SDK Version: 40.0.1
  2. Platforms(Android/iOS/web/all): Android / iOS

Originally posted on Stack Overflow:

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?

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.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.