1

I want to test the api call and data returned which should be displayed inside my functional component. I have a component that calls an API when it is first loaded and when certain things change i.e when typing.

I have a useEffect calling the API like so:

useEffect(() => {
    const query = queryString;

    const apiRequest = async () => {
      try {
        setIsFetching(true);
        const response = await getData(query, page);

        setData(response.data);
      } catch (error) {
        // Do some error
        console.log('error');
      } finally {
        setIsFetching(false);
      }
    };

    apiRequest();
  }, [queryString, page]);

getData is an axios function like so:

let getDataRequest;
const getData = (searchQuery = null, page = PAGE, size = PAGE_SIZE) => {
  if (getDataRequest) getDataRequest.cancel();

  getDataRequest = axios.CancelToken.source();

  return axios.get('url_to_api', {
    params: {
      page,
      searchQuery,
      size,
    },
    cancelToken: getDataRequest.token,
  });
};

When trying to test this component I am running into the error When testing, code that causes React state updates should be wrapped into act(...):

I have been trying to follow first link also second link third link and many more pages but still no luck.

Here is one version of the test I am still seeing the error:

it('should render data', async () => {
    let container;
    act(async () => {
      await getData.mockResolvedValueOnce({
        data: { things: data, meta: { current_page: 1 } },
      });
      container = render(<Component />);
    });

    await waitFor(() => container.queryByText('Text I would expect after api call'));
  }) 

I have also tried mocking the function in my test file like so:

import { getData } from './dataAccess';

const mockedData = { data: { things: data } };

jest.mock('./api', () => ({
  getData: jest
    .fn()
    .mockImplementation(() => new Promise(resolve => resolve(mockedData))),
}));

I am using import { act } from 'react-dom/test-utils'; with enzyme and jest. I also am using '@testing-library/react';

saunders
  • 969
  • 4
  • 14
  • 25

0 Answers0