测试使用useEffect挂钩和apollo的自定义上下文挂钩

时间:2019-09-26 11:36:11

标签: javascript reactjs react-hooks react-testing-library react-hooks-testing-library

我创建了一个上下文,该上下文公开了一个易于使用的钩子。 在此挂钩中,我已经确保在呈现页面之前已预先加载了一些数据,如下所示:

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 };

我想使用 testing-library 对此进行测试,阅读一些文章和github问题后,我得出以下结论:

const包装器=({儿童})=>(                           {儿童}               );

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");
});

可悲的是说当前为空。我期望这是因为useEffect导致状态更新,因此首先返回null(默认值)。在更新之前。这就是为什么我介绍waitForNextUpdate的原因。

但是,这给了我以下错误:

警告:传递给TestRenderer.act(...)函数的回调不得返回任何内容。

  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 */

关于如何解决此问题的任何想法?

1 个答案:

答案 0 :(得分:3)

在阅读https://dev.to/theactualgivens/testing-react-hook-state-changes-2oga之后,我决定模拟useReducer,因为分派会导致useEffect挂钩中的状态更新。之后,它起作用了。现在,我模拟了reducer的初始状态。

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

我的测试看起来像

it('should render', async () => {
  const { result } = renderHook(useMyContext, { wrapper: bySlugWrapper });
  expect(result.current.somevar).toEqual(MY_CONTEXT.somevar);
});