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?
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' }];
setMovies(movies);
}, 1000);
}, []);
return (
<div>
{movies.length > 0 && (
<div>
{movies.map((x) => (
<div data-testid='movies'>{x.title}</div>
))}
</div>
)}
</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');
expect(movieTiles).toHaveLength(2);
});
Here is the error from the test