Skip to content

Commit 9cc7c82

Browse files
committed
fix(Page): handle failed dynamic content loading safely
test(Page): add unit test for content.__error rendering and fix test setup
1 parent 67c9963 commit 9cc7c82

2 files changed

Lines changed: 54 additions & 2 deletions

File tree

src/components/Page/Page.jsx

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,9 @@ export default function Page(props) {
3030
);
3131
const content = isDynamicContent
3232
? dynamicContent
33-
: props.content.default || props.content;
33+
: props.content && props.content.default !== undefined
34+
? props.content.default
35+
: props.content;
3436

3537
const [contentLoaded, setContentLoaded] = useState(!isDynamicContent);
3638

@@ -41,7 +43,13 @@ export default function Page(props) {
4143
setContent(() => mod.default || mod);
4244
setContentLoaded(true);
4345
})
44-
.catch(() => setContent("Error loading content."));
46+
.catch(() => {
47+
setContent({
48+
__error: true,
49+
message: "Failed to load page content.",
50+
});
51+
setContentLoaded(true);
52+
});
4553
}
4654
}, [props.content]);
4755

@@ -94,6 +102,10 @@ export default function Page(props) {
94102

95103
if (typeof content === "function") {
96104
contentRender = content({}).props.children;
105+
} else if (content && content.__error) {
106+
contentRender = (
107+
<div className="text-red-600 font-bold">{content.message}</div>
108+
);
97109
} else {
98110
contentRender = (
99111
<div
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @jest-environment jsdom
3+
*/
4+
5+
import React from "react";
6+
import { render, screen } from "@testing-library/react";
7+
import "@testing-library/jest-dom";
8+
import { MemoryRouter } from "react-router";
9+
import Page from "../Page";
10+
11+
// Mock components that cause unrelated failures
12+
jest.mock("../../Contributors/Contributors.jsx", () => () => <div />);
13+
jest.mock("../../PageLinks/PageLinks.jsx", () => () => <div />);
14+
15+
// Mock react-router hook used inside Page
16+
jest.mock("react-router", () => ({
17+
...jest.requireActual("react-router"),
18+
useLocation: () => ({ pathname: "/test", hash: "" }),
19+
}));
20+
21+
// Mock scrollTo (jsdom doesn't support it)
22+
window.scrollTo = jest.fn();
23+
24+
describe("Page component", () => {
25+
it("renders error message when content.__error exists", async () => {
26+
const content = {
27+
__error: true,
28+
message: "Failed to load content",
29+
};
30+
31+
render(
32+
<MemoryRouter>
33+
<Page content={content} title="Test" path="/test" />
34+
</MemoryRouter>,
35+
);
36+
37+
const errorElement = await screen.findByText(/failed to load content/i);
38+
expect(errorElement).toBeInTheDocument();
39+
});
40+
});

0 commit comments

Comments
 (0)