Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing a custom context hook that uses a useEffect hook and apollo

I have created a context that exposes a hook for ease of use. Within this hook i already make sure that some data is preloaded before rendering the page, like this:

export const MyContext = React.createContext({} as any);

function useMyContext() {
  const context = React.useContext(MyContext);
  if (context === undefined) {
    throw new Error('useMyContext must be used within a MyContext');
  }
  return context;
}

function MyContextProvider(props: any) {
  const client = useApolloClient();
  const { user } = React.useContext(UserContext);
  const [data, setData ] = React.useState({});

  const findSomethingFromUser = () => {
    return client.query({
      query: FIND_SOMETHING_FROM_USER,
      variables: { userId: user.id },
    });
  };

  const load = () => {
    findSomethingFromUser()
      .then(({ data, errors }) => {
          setData(data);
      });
  };

  // Load user test
  React.useEffect(load, []);

  return (
    <MyContext.Provider value={{ data }}>
        {children}
    </MyContext.Provider>
  );
}

export { MyContextProvider, useMyContext };

I would like to test this using testing-library and after reading some articles and github issues i came to the following:

const wrapper = ({ children }) => ( {children} );

it('should fetch the special user value', async () => {
    const { result, waitForNextUpdate } = renderHook(useMyContext, { wrapper });

    await waitForNextUpdate();

    // await act(async () => {
    //     await waitForNextUpdate();
    //   });

    expect(result.current.mySpecialUserValue).toEqual("something");
});

Where it sadly says that the current is null. I expect this is because the useEffect causes a state update and thus returns a null (default value) first. before updating. That's why i introduced the waitForNextUpdate.

However with this it gives me the following error:

Warning: The callback passed to TestRenderer.act(...) function must not return anything.

  It looks like you wrote TestRenderer.act(async () => ...) or returned a Promise from it's callback. Putting asynchronous logic inside TestRenderer.act(...) is not supported.

console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:102
  Warning: Do not await the result of calling TestRenderer.act(...), it is not a Promise.
console.error node_modules/react-test-renderer/cjs/react-test-renderer.development.js:102
  Warning: An update to MyContextProvider inside a test was not wrapped in act(...).

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

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

Any ideas on how to resolve this?

like image 330
Maxim Avatar asked Oct 15 '22 10:10

Maxim


1 Answers

After reading https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga I decided to mock the useReducer as the dispatches cause state updates in the useEffect hook. After that it worked. I now mock the reducer initial state.

const dispatch = jest.fn();
const useReducerSpy = jest.spyOn(React, 'useReducer');
useReducerSpy.mockImplementation((init: any) => [MY_CONTEXT_MOCK, dispatch]);

and my test looks like

it('should render', async () => {
  const { result } = renderHook(useMyContext, { wrapper: bySlugWrapper });
  expect(result.current.somevar).toEqual(MY_CONTEXT.somevar);
});
like image 66
Maxim Avatar answered Oct 26 '22 23:10

Maxim