,children:[{path:"/",element:< ProfileList/>,loader:profileListL"> When testing with Jest, this header only appears when using useLoaderData in the data router-PHP Chinese Network Q&A
When testing with Jest, this header only appears when using useLoaderData in the data router
P粉440453689
P粉440453689 2023-09-21 11:51:20
0
1
472

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 routerand 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.

P粉440453689
P粉440453689

reply all (1)
P粉364129744

Even in unit tests, components accessing the data API should still be rendered within the data router. In unit testing, it is recommended to useMemoryRouter(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(); });
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!