Skip to content

Instantly share code, notes, and snippets.

@codeape2
Last active October 5, 2022 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeape2/53525e071afe13f2e31571bc4d8fc78f to your computer and use it in GitHub Desktop.
Save codeape2/53525e071afe13f2e31571bc4d8fc78f to your computer and use it in GitHub Desktop.
My failed attempt at creating at test for the route loader behaviour bug
import * as React from "react";
import * as ReactDOM from "react-dom/client";
import { act } from "react-dom/test-utils";
import {
createMemoryRouter,
Outlet,
RouterProvider,
createHashRouter,
useNavigate,
createBrowserRouter
} from "react-router-dom";
let loaderInvocations = [];
function recordLoaderInvocation(routeName) {
loaderInvocations.push(routeName);
console.log(loaderInvocations);
return routeName;
}
function RootRouteElement() {
const navigate = useNavigate();
return <>
<button id="c1btn" onClick={() => navigate({pathname: "children/1"})}>Navigate to child 1</button>
<button id="c2btn" onClick={() => navigate({pathname: "children/2"})}>Navigate to child 2</button>
<button>Navigate to child 1 with qstring</button>
<button>Navigate to child 2 with qstring</button>
<Outlet/>
</>;
}
function createRoutes() {
return [
{
path: "/",
loader: () => recordLoaderInvocation("root"),
element: <RootRouteElement/>,
children: [
{
path: "children",
loader: () => recordLoaderInvocation("children"),
children: [
{
path: ":childid",
loader: ({params}) => recordLoaderInvocation(`child ${params.childid}`),
element: <div>Child</div>
}
]
}
]
}
];
}
let container;
beforeEach(() => {
loaderInvocations = [];
container = document.createElement('div');
document.body.appendChild(container);
});
afterEach(() => {
//console.log("removing container");
document.body.removeChild(container);
container = null;
});
describe("Route loaders", () => {
test("execute only when neccessary", () => {
act(() => {
ReactDOM.createRoot(container).render(<RouterProvider router={createBrowserRouter(createRoutes())} fallbackElement={<p>FALLBACK!</p>}/>);
console.log(container.outerHTML);
expect(loaderInvocations).toEqual(['root']);
});
const c1btn = container.querySelector("#c1btn");
expect(c1btn).not.toBeNull();
expect(c1btn.innerText).toEqual("Navigate to child 1");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment