使用React Router v6.14.2,我已经完成了设置浏览器路由的所有步骤
index.jsx
const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    children: [
      {
        path: "/",
        element: <ProfileList />,
        loader: profileListLoader,
      },
    ],
  },
]);
const root = ReactDOM.createRoot(
  document.getElementById("root") as HTMLElement
);
root.render(<RouterProvider router={router} />);
然后,当我想在我的React组件中使用数据加载器时,代码如下
profileList.jsx
const ProfileList: React.FC = () => {
  const users = useLoaderData();
  return (
    <div data-testid={"profiles"}>
      {users.map((user: User) => (
        <Link to={`/profile/${user.id}`}>
          <ProfileDetailView user={user} />
        </Link>
      ))}
    </div>
  );
};
export const profileListLoader = async () => {
  return fakeUsers as User[];
};
export default ProfileList;
在本地运行应用程序时,这个方法非常有效,用户正在加载,控制台或其他地方没有任何问题。
但是,当我尝试运行jest测试时,我收到以下错误信息
useLoaderData必须在数据路由器中使用
并且指向以下代码行
const users = useLoaderData();
目前,测试非常简单,但仍然导致测试失败。
profile.test.js
test("Render profile list", () => {
  beforeEach(() => fetch.mockClear());
  render(<ProfileList />);
  const profileList = screen.getByTestId("profiles");
  expect(profileList).toBeInTheDocument();
});
我尝试查看React Router的文档并且严格按照其中的步骤进行操作。我在Stack Overflow上进行了搜索,但没有找到与我的问题完全匹配的内容。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
即使在单元测试中,访问数据API的组件仍然应该在数据路由器内渲染。在单元测试中,建议使用
MemoryRouter(例如:createMemoryRouter),因为Node不是一个DOM环境。示例:
test("Render profile list", () => { beforeEach(() => fetch.mockClear()); const router = createMemoryRouter( [{ path: "/", element:  }],
    { initialEntries: ["/"] },
  );
  render( );
  const profileList = screen.getByTestId("profiles");
  expect(profileList).toBeInTheDocument();
});