fix: 试卷打印页加载失败展示错误态与返回试卷入口

- 区分加载中与加载失败,失败时显示明确提示并返回试卷详情
- 留白下拉补齐无障碍标签
- 补充错误态单元测试
Refs: https://github.com/margrop/wrong-notebook/issues/141
This commit is contained in:
margrop
2026-12-04 04:17:07 +08:00
parent 5275ba5690
commit a9e3fbb5bb
4 changed files with 78 additions and 3 deletions

View File

@@ -0,0 +1,57 @@
/**
* 试卷打印页加载失败状态:不再永久停在「加载中」,展示错误提示与返回试卷入口
*/
import { act } from "react";
import { createRoot } from "react-dom/client";
import type { Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import ExamPrintPage from "@/app/exams/[id]/print/page";
import { LanguageProvider } from "@/contexts/LanguageContext";
import { translations } from "@/lib/translations";
const mocks = vi.hoisted(() => ({ get: vi.fn() }));
vi.mock("@/lib/api-client", () => ({ apiClient: { get: mocks.get, patch: vi.fn() } }));
vi.mock("next/navigation", () => ({ useParams: () => ({ id: "paper-1" }) }));
vi.mock("@/components/ui/back-button", () => ({
BackButton: ({ fallbackUrl }: { fallbackUrl: string }) => <a href={fallbackUrl}>返回试卷</a>,
}));
let container: HTMLDivElement;
let root: Root;
async function flush() {
await act(async () => {
const { promise, resolve } = Promise.withResolvers<void>();
setTimeout(resolve, 0);
await promise;
});
}
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
localStorage.clear();
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
});
afterEach(async () => {
await act(async () => root.unmount());
container.remove();
vi.unstubAllGlobals();
});
describe("试卷打印页加载失败", () => {
it("展示错误提示与返回试卷入口,不再显示加载中", async () => {
mocks.get.mockRejectedValue(new Error("404"));
await act(async () => root.render(<LanguageProvider><ExamPrintPage /></LanguageProvider>));
await flush();
expect(container.textContent).toContain(translations.zh.exam.printLoadFailed);
expect(container.textContent).toContain(translations.zh.exam.printLoadFailedHint);
expect(container.textContent).not.toContain(translations.zh.common.loading);
expect(container.querySelector('a[href="/exams/paper-1"]')).toBeTruthy();
});
});

View File

@@ -34,6 +34,7 @@ export default function ExamPrintPage() {
const params = useParams();
const { t, language } = useLanguage();
const [paper, setPaper] = useState<ExamPaperDetail | null>(null);
const [loadError, setLoadError] = useState(false);
usePageTitle(t.exam.title, paper?.title, t.pageTitle.examPrint);
// 「包含答案页」默认不勾选,选择结果记在本机浏览器,下次打印沿用
const [includeAnswers, setIncludeAnswers] = useStoredChoice(EXAM_PRINT_INCLUDE_ANSWERS_STORAGE_KEY, ["1", "0"] as const, "0");
@@ -130,10 +131,23 @@ export default function ExamPrintPage() {
useEffect(() => {
apiClient.get<ExamPaperDetail>(`/api/exams/${params.id}`)
.then(setPaper)
.catch(() => setPaper(null));
.catch(() => setLoadError(true));
}, [params.id]);
if (!paper) return <div className="p-8 text-center">{t.common.loading}</div>;
if (!paper) {
if (loadError) {
return (
<main className="min-h-screen bg-white p-8">
<div className="mx-auto flex max-w-xl flex-col items-center gap-4 text-center">
<p className="font-semibold">{t.exam.printLoadFailed}</p>
<p className="text-sm text-muted-foreground">{t.exam.printLoadFailedHint}</p>
<BackButton fallbackUrl={`/exams/${params.id}`} />
</div>
</main>
);
}
return <div className="p-8 text-center">{t.common.loading}</div>;
}
const figureQuestions = paper.questions.filter((question) => question.status === "ready" && question.questionText && Boolean(question.figureSvg || question.figureImage || question.figureUploadImage));
const readyCount = paper.questions.filter((question) => question.status === "ready" && question.questionText).length;
@@ -193,7 +207,7 @@ export default function ExamPrintPage() {
<div className="flex items-center gap-2 text-sm">
<span className="shrink-0">{t.exam.answerSpace}</span>
<Select value={answerSpace} onValueChange={changeAnswerSpace}>
<SelectTrigger className="h-8 w-40">
<SelectTrigger className="h-8 w-40" aria-label={t.exam.answerSpace}>
<SelectValue />
</SelectTrigger>
<SelectContent>

View File

@@ -2133,6 +2133,8 @@ export const en = {
notFound: "Exam not found",
back: "Back",
printTitle: "Print Preview",
printLoadFailed: "Failed to load the exam",
printLoadFailedHint: "The exam may have been deleted or the network is unavailable. Return to the exam details and try again.",
includeAnswers: "Include answer key",
showQuestionMarkers: "Print a locating QR code per question",
answerSpace: "Answer space",

View File

@@ -2132,6 +2132,8 @@ export const zh = {
notFound: "试卷不存在",
back: "返回",
printTitle: "打印预览",
printLoadFailed: "试卷加载失败",
printLoadFailedHint: "试卷可能已被删除,或网络连接异常。请返回试卷详情后重试。",
includeAnswers: "包含答案页",
showQuestionMarkers: "每题打印定位二维码",
answerSpace: "留白",