Using initialEntries with MemoryRouter for testing #12287
-
Hi, I have a component that gets some params from the URL with
What does it mean? Why they are not supported? What am I supposed to do with this warning? Here is my custom render code (simplified) import { render } from '@testing-library/react';
import { type PropsWithChildren, type FC } from 'react';
import { MemoryRouter } from 'react-router-dom';
const RouterProvider: FC<PropsWithChildren<{ initialURL?: string }>> = ({
children,
initialURL,
}) => {
return (
<MemoryRouter initialEntries={initialURL ? [initialURL] : undefined}>
{children}
</MemoryRouter>
);
};
type CustomProviderOptions = {
initialURL?: string;
};
const getProviders =
(customProviderOptions: CustomProviderOptions = {}) =>
({ children }: PropsWithChildren) => {
return (
<RouterProvider initialURL={customProviderOptions.initialURL}>
{children}
</RouterProvider>
);
};
const customRender = (
ui: Parameters<typeof render>[0],
{
customOptions,
...options
}: Parameters<typeof render>[1] & { customOptions: CustomProviderOptions }
): ReturnType<typeof render> =>
render(ui, { wrapper: getProviders(customOptions), ...options });
export * from '@testing-library/react';
export { customRender as render }; Usage example: render(
<MyComponentThatWantsParamsFromURL />,
{ customOptions: { initialURL: "http://localhost/hierarchymanagement/1/nodes" } }
); UPD: alright, I see that entries that start from the "/" i.e. just pathnames, without the full URL do not trigger the warning. But I can't see that UPD2: ok, I actually don't set my appRoutes that specify what to render for each route, which kinda makes sense if I do not want to test/render the whole page but only a component under specific path. But then I'm not sure if I even can make useParams work without mocking them. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ok, I think I figured it out, so for initialEntries, just use paths only starting with a slash. For useParams to work your test should include some routing definition. Example // TestableComponentWithUseParamsHookInside.spec.tsx
render(
<MemoryRouter initialEntries={['/1111']}>
<Routes>
<Route
element={
<TestableComponentWithUseParamsHookInside />
}
path=":paramName" // should specify the params your component wants from the URL
/>
</Routes>
</MemoryRouter>
);
// TestableComponentWithUseParamsHookInside.tsx
export function TestableComponentWithUseParamsHookInside() {
const {paramName} = useParams<{ paramName: string }>();
// .... |
Beta Was this translation helpful? Give feedback.
Ok, I think I figured it out, so for initialEntries, just use paths only starting with a slash. For useParams to work your test should include some routing definition. Example