jeudi 4 mars 2021

Writing integration test for asynchronous code in React application with Context and useEffect

So, in useEffect I am fetching an object from the API then I am dispatching response data to the Context reducer and then updating the state. It looks something like this:

export const fetchItem = (id) => request({url: `/items/${id}`, method: 'get'});

...

const {dispatch, singleItem} = useProvider();
    
useEffect(() => {
        const id = getItemIdFromUrl(props);
        fetchItem(id).then((response) => {
          dispatch(action(response.data.data));
        });
      }, [props, dispatch]);

I would like to write a good integration test for this. I am using react-testing-library with Jest. I am trying to mock the return value of the fetchItem function and then to check if everything is rendered correctly but constantly getting this warning:

act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

Any chance to do this correctly?

Aucun commentaire:

Enregistrer un commentaire