Skip to content
Advertisement

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…

JavaScript

Here is the full test code…

JavaScript

Here is the error from the test

enter image description here

Advertisement

Answer

You should use Fake Timers when your code uses timers (setTimeout, setInterval, clearTimeout, clearInterval).

Use jest.advanceTimersByTime(1000) to move ahead in time by 1000ms.

Don’t forget act() helper function:

When writing UI tests, tasks like rendering, user events, or data fetching can be considered as “units” of interaction with a user interface. react-dom/test-utils provides a helper called act() that makes sure all updates related to these “units” have been processed and applied to the DOM before you make any assertions:

Since we run the setState function that will change the component state 1000ms ahead of time, we must wrap this operation (jest.advanceTimersByTime(1000)) in the act() function.

Otherwise, you will get warning:

Warning: An update to App inside a test was not wrapped in act(…).

When testing, code that causes React state updates should be wrapped into act(…):

E.g.

App.jsx:

JavaScript

App.test.jsx:

JavaScript

test result:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement