如何使用反冲为自定义钩子编写测试代码

How to write test code for custom hook using recoil

我正在使用 Jest 为我的 Web 应用程序中的自定义挂钩编写测试代码。

它使用Recoil做状态管理,但是我运行 npm run test.

时出现错误信息

这是错误信息。

 This component must be used inside a <RecoilRoot> component.

      16 | const useIds = () => {
      17 |   // const [ids, setIds] = React.useState([]);
    > 18 |   const [ids, setIds] = useRecoilState(idsState);
         |                         ^

这是测试代码。

import * as React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { useIds } from '@/hooks/useIds';
import { RecoilRoot } from 'recoil';

it('unit test for custom hook useIds', () => {
  const TestComponent: React.FC = () => {
    const ids = useIds();

    return (
      <RecoilRoot>
        <div title='ids'>{ ids }</div>
      </RecoilRoot>
  )
  }

  const { getByTitle } = render(<TestComponent />);
  const ids = getByTitle('ids');
})

这是自定义挂钩代码

import * as React from 'react';
import { useRouter } from 'next/router';
import { atom, useRecoilState } from 'recoil';

import { fetchIdsByType } from '@/repositories';

const initialState: {
  [type: string]: number[];
} = {};

export const idsState = atom({
  key: 'idsState',
  default: initialState,
});

const useIds = () => {
  const [ids, setIds] = useRecoilState(idsState);
  const router = useRouter();
  const { type } = router.query;

  React.useEffect(() => {
    if (router.asPath !== router.route) {
      // @ts-ignore
      fetchIdsByType(type).then((ids: number[]) => {
        setIds((prevState) => {
          return {
            ...prevState,
            // @ts-ignore
            [type]: ids,
          };
        });
      });
    }
  }, [router]);

  // @ts-ignore
  return ids[type];
};

export { useIds };

我知道为什么会发生错误,但我不知道 RecoilRoot 应该在哪里?

您可能需要将使用自定义挂钩的组件放置在何处,如下所示:

it('unit test for custom hook useIds', () => {
  const TestComponent: React.FC = () => {
    const ids = useIds();

    return (
      <div title='ids'>{ ids }</div>
    )
  }

  const { getByTitle } = render(
    // Put it here to wrap your custom hook
    <RecoilRoot>
      <TestComponent />
    </RecoilRoot>
  );
  const ids = getByTitle('ids');
})