,children:[{path:"/",element:< ProfileList/>,loader:profileListL">
Using React Router v6.14.2, I have completed all the steps to set up browser routing
index.jsx
const router = createBrowserRouter([ { path: "/", element:, children: [ { path: "/", element: , loader: profileListLoader, }, ], }, ]); const root = ReactDOM.createRoot( document.getElementById("root") as HTMLElement ); root.render( );
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 ({users.map((user: User) => (); }; 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 messageuseLoaderData must be used in the data router
and point to the following line of codeconst 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(); 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.
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: