React Testing Library does not find elements using getAllByTestId after initial render

I have a very simple component where I am trying to simulate an API call to get some movies with a slight delay.

I want to write a test which tests that the movies are gathered and then rendered to screen.

I am trying to use screen.getAllByTestId to do this, however it always fails. It is as if it doesn't re-render and therefore does not get the updated change.

I have added a testid onto the elements and can see these in the DOM.

Can anyone help as to why this isn't finding them after they appear?

enter image description here

Here is the full component code...

import './App.css';
import { useEffect, useState } from 'react';

function App() {
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    // simulate API call to get
    setTimeout(() => {
      const movies = [{ title: 'Titanic' }, { title: 'Back To The Future' }];
    }, 1000);
  }, []);

  return (
      {movies.length > 0 && (
          { => (
            <div data-testid='movies'>{x.title}</div>

export default App;

Here is the full test code...

import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
  render(<App />);
  const movieTiles = screen.getAllByTestId('movies');

Here is the error from the test

enter image description here

Read more here:

Content Attribution

This content was originally published by user3284707 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: