1

I have this test:


const renderComponent = () =>

   act(() => {
      render(
           <MemoryRouter>
               <HomePage/>
               <ErrorPage/>
           </MemoryRouter>
       )
   }
)


it('Should render the Home page if the item is successfully retrieved', async () => {



        act(() => {

            global.fetch = jest.fn(() =>
                Promise.resolve({
                    json: () => [{item: 'item1'}]
                })
            ) as jest.Mock

            renderComponent()
        })

            expect(await waitFor(() => screen.getByTestId('HomePage'))).toBeInTheDocument()
    });

The test itself passes but I get this console error:

   When testing, code that causes React state updates should be wrapped into act(...):
      
      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

It highlights the setItem section of the code as being the issue:

  useEffect(() => {
        fetch(`http://localhost:4000/items`)
            .then(response => response.json())
            .then(data => {
                setItem(data)
            }) }, [])

I'm mystified as to what is going on

Nespony
  • 1,253
  • 4
  • 24
  • 42
  • Found this related - https://stackoverflow.com/questions/55047535/testing-react-components-that-fetches-data-using-hooks/59839513#59839513 – Naveen Nov 13 '22 at 16:24
  • What happens when you use `findByTestId` instead of waitfor? Like `expect(await screen.findByTestId('HomePage')).toBeInTheDocument()` – NeERAJ TK Nov 13 '22 at 16:29

0 Answers0