Using React Router v6.14.2, I have completed all the steps to set up browser routing
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} />);
Then when I want to use the data loader in my React component, the code is as follows
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;
This method works perfectly when running the application locally and the user is loading without any issues in the console or elsewhere.
However, when I try to run jest tests, I get the following error message
useLoaderData must be used in the data router
and point to the following line of code
const users = useLoaderData();
Currently, the test is very simple, but it still causes the test to fail.
profile.test.js
test("Render profile list", () => { beforeEach(() => fetch.mockClear()); render(<ProfileList />); const profileList = screen.getByTestId("profiles"); expect(profileList).toBeInTheDocument(); });
I tried to look at the documentation for React Router and followed the steps exactly. I've searched on Stack Overflow but haven't found anything that exactly matches my question.
P粉3641297442023-09-22 11:02:01
Even in unit tests, components accessing the data API should still be rendered within the data router. In unit testing, it is recommended to use MemoryRouter
(for example: createMemoryRouter
) because Node is not a DOM environment.
Example:
test("Render profile list", () => { beforeEach(() => fetch.mockClear()); const router = createMemoryRouter( [{ path: "/", element:}], { initialEntries: ["/"] }, ); render( ); const profileList = screen.getByTestId("profiles"); expect(profileList).toBeInTheDocument(); });