javascriptreactjsjestjsreact-testing

Why did my asynchronous test in react not work?


Im testing a react component with jest and the react testing library (newest versions) and i dont get the asynchron tests to work. I assume its a syntax problem. The component gets rendert correctly, and the fetch (useEffect) also seems to work due to the fact that the time out works.

test('renders asynchron', async () => {
   renderComp(); //renders component
   
   await waitFor(() => expect(screen.findByTestId('testid')).toBeInTheDocument()); //dont work
   await screen.findByTestId('testid'); //same

   setTimeout(() => {
      expect(screen.findByTestId('testid')).toBeInTheDocument(); //this works
   }, 100);

});

Also i got the same issue if i expect an element after an button click.


Solution

  • because following arrow function is not awaitable:

    () => expect(screen.findByTestId('testid')).toBeInTheDocument()
    

    you must Define inner function async and await for.