From d3e2ad27be1e1c5fb933df09b20f5ea8ab4da964 Mon Sep 17 00:00:00 2001 From: margrop <1731827+margrop@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:09:20 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E5=85=B1=E4=BA=AB=E9=A2=98=E5=BA=93?= =?UTF-8?q?=E5=AF=BC=E5=85=A5=E6=94=AF=E6=8C=81=E5=90=8C=E6=97=B6=E5=86=99?= =?UTF-8?q?=E5=85=A5=E9=94=99=E9=A2=98=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 共享题库导入增加「同时写入错题本」与目标错题本选择 - 补充组件交互测试 Refs: https://github.com/margrop/wrong-notebook/issues/41 --- .../unit/shared-bank-picker.test.tsx | 125 ++++++++++++++++++ src/app/banks/page.tsx | 2 +- src/components/banks/shared-bank-picker.tsx | 60 ++++++++- 3 files changed, 180 insertions(+), 7 deletions(-) create mode 100644 src/__tests__/unit/shared-bank-picker.test.tsx diff --git a/src/__tests__/unit/shared-bank-picker.test.tsx b/src/__tests__/unit/shared-bank-picker.test.tsx new file mode 100644 index 00000000..5b07aa3d --- /dev/null +++ b/src/__tests__/unit/shared-bank-picker.test.tsx @@ -0,0 +1,125 @@ +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 { SharedBankPicker } from '@/components/banks/shared-bank-picker'; +import { LanguageProvider } from '@/contexts/LanguageContext'; +import { apiClient } from '@/lib/api-client'; +import { toast } from '@/lib/feedback'; +import type { Notebook } from '@/types/api'; + +vi.mock('@/lib/api-client', () => ({ apiClient: { post: vi.fn() } })); +vi.mock('@/lib/frontend-logger', () => ({ frontendLogger: { warn: vi.fn(), error: vi.fn() } })); +vi.mock('@/lib/feedback', () => ({ toast: { success: vi.fn(), error: vi.fn() } })); + +const index = { + format: 'wrong-notebook-question-bank-index', + version: 1, + updatedAt: '2026-11-29', + packages: [ + { id: 'p1', title: '小学数学题库', stage: 'primary', subject: 'math', count: 1, source: 'test', license: 'MIT', file: 'banks/a.json' }, + ], +}; + +const bankFile = { + format: 'wrong-notebook-question-bank', + version: 1, + meta: { id: 'p1', title: '小学数学题库', stage: 'primary', subject: 'math', source: 'test', license: 'MIT' }, + questions: [{ text: '1 + 1 = ?', answer: '2' }], +}; + +const notebook: Notebook = { + id: 'nb1', + name: '我的错题本', + userId: 'u1', + createdAt: '2026-11-01T00:00:00.000Z', + updatedAt: '2026-11-01T00:00:00.000Z', +}; + +let container: HTMLDivElement; +let root: Root; + +beforeEach(() => { + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + vi.stubGlobal('fetch', vi.fn(async (url: string) => ({ + ok: true, + json: async () => (String(url).includes('index.json') ? index : bankFile), + }))); + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); +}); + +afterEach(async () => { + await act(async () => root.unmount()); + container.remove(); + vi.unstubAllGlobals(); +}); + +async function flushUntil(predicate: () => boolean) { + for (let i = 0; i < 50; i += 1) { + if (predicate()) return; + await act(async () => { await Promise.resolve(); }); + } + throw new Error('等待渲染超时'); +} + +async function render(notebooks: Notebook[]) { + await act(async () => root.render( + + + , + )); + await flushUntil(() => container.textContent?.includes('小学数学题库') ?? false); +} + +function findImportButton() { + const button = [...container.querySelectorAll('button')].find((item) => item.textContent?.trim() === '导入'); + if (!button) throw new Error('未找到导入按钮'); + return button; +} + +describe('共享题库导入', () => { + it('勾选同时写入错题本后提交目标错题本', async () => { + vi.mocked(apiClient.post).mockResolvedValue({ bank: { name: '小学数学题库', questionCount: 1 }, errorItemsCreated: 1, duplicates: 0 }); + await render([notebook]); + + const checkbox = container.querySelector('input[type="checkbox"]')!; + await act(async () => checkbox.click()); + expect(container.textContent).toContain('目标错题本'); + + await act(async () => findImportButton().click()); + await flushUntil(() => vi.mocked(apiClient.post).mock.calls.length > 0); + + expect(apiClient.post).toHaveBeenCalledWith( + '/api/question-banks', + expect.objectContaining({ addToErrorItems: true, notebookId: 'nb1' }), + expect.objectContaining({ timeout: 300_000 }), + ); + }); + + it('不勾选时只导入题库,不写入错题本', async () => { + vi.mocked(apiClient.post).mockResolvedValue({ bank: { name: '小学数学题库', questionCount: 1 }, errorItemsCreated: 0, duplicates: 0 }); + await render([notebook]); + + await act(async () => findImportButton().click()); + await flushUntil(() => vi.mocked(apiClient.post).mock.calls.length > 0); + + expect(apiClient.post).toHaveBeenCalledWith( + '/api/question-banks', + expect.objectContaining({ addToErrorItems: false, notebookId: undefined }), + expect.objectContaining({ timeout: 300_000 }), + ); + }); + + it('勾选但无错题本时提示选择目标错题本', async () => { + await render([]); + + const checkbox = container.querySelector('input[type="checkbox"]')!; + await act(async () => checkbox.click()); + await act(async () => findImportButton().click()); + + expect(toast.error).toHaveBeenCalledWith('勾选「同时写入错题本」后需选择目标错题本。'); + expect(apiClient.post).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/banks/page.tsx b/src/app/banks/page.tsx index 227994a0..309916df 100644 --- a/src/app/banks/page.tsx +++ b/src/app/banks/page.tsx @@ -71,7 +71,7 @@ export default function BanksPage() { {isAdmin ? ( <> - bank.name)} onImported={fetchBanks} /> + bank.name)} notebooks={notebooks} onImported={fetchBanks} /> ) : (

{t.banks.adminManagedHint}

diff --git a/src/components/banks/shared-bank-picker.tsx b/src/components/banks/shared-bank-picker.tsx index 96765ffa..61b61cb9 100644 --- a/src/components/banks/shared-bank-picker.tsx +++ b/src/components/banks/shared-bank-picker.tsx @@ -14,6 +14,7 @@ import { bankPackageUrl, parseBankFile, parseBankIndex } from "@/lib/question-ba import { DEFAULT_BANK_INDEX_URL } from "@/lib/question-bank/types"; import type { BankIndexPackage } from "@/lib/question-bank/types"; import type { BankImportResult } from "@/lib/question-bank/types"; +import type { Notebook } from "@/types/api"; const STAGE_KEYS: Record = { primary: "primary", @@ -25,17 +26,27 @@ const STAGE_KEYS: Record void; } -/** 从共享题库仓库读取索引并逐包导入;只进入真题库,不写入错题 */ -export function SharedBankPicker({ existingNames, onImported }: SharedBankPickerProps) { +/** 从共享题库仓库读取索引并逐包导入;可选同时把整包题目写入自己的错题本 */ +export function SharedBankPicker({ existingNames, notebooks, onImported }: SharedBankPickerProps) { const { t } = useLanguage(); const importedNames = new Set(existingNames.map((name) => name.trim())); const [packages, setPackages] = useState([]); const [loading, setLoading] = useState(true); const [failed, setFailed] = useState(false); const [importingId, setImportingId] = useState(null); + const [addToErrorItems, setAddToErrorItems] = useState(false); + const [notebookId, setNotebookId] = useState(notebooks[0]?.id ?? ""); + + // 错题本异步加载:首个错题本到达后补齐默认目标,避免勾选后仍提示未选择 + useEffect(() => { + // eslint-disable-next-line react-hooks/set-state-in-effect -- 依赖异步加载的错题本列表 + if (!notebookId && notebooks[0]) setNotebookId(notebooks[0].id); + }, [notebooks, notebookId]); const loadIndex = useCallback(async () => { setLoading(true); @@ -60,6 +71,10 @@ export function SharedBankPicker({ existingNames, onImported }: SharedBankPicker }, [loadIndex]); const handleImport = async (item: BankIndexPackage) => { + if (addToErrorItems && !notebookId) { + toast.error(t.banks.notebookRequired); + return; + } setImportingId(item.id); try { const response = await fetch(bankPackageUrl(DEFAULT_BANK_INDEX_URL, item.file), { cache: "no-store", signal: AbortSignal.timeout(30_000) }); @@ -70,11 +85,20 @@ export function SharedBankPicker({ existingNames, onImported }: SharedBankPicker const result = await apiClient.post("/api/question-banks", { file: raw, name: parsed.data.meta.title, - addToErrorItems: false, + addToErrorItems, + notebookId: addToErrorItems ? notebookId : undefined, }, { timeout: 300_000, recoverable: true }); - toast.success((t.banks.imported || "Imported {name} with {count} questions.") - .replace("{name}", result.bank.name) - .replace("{count}", String(result.bank.questionCount))); + const message = addToErrorItems + ? (t.banks.importedWithItems || "Imported {name} with {count} questions; {items} added, {duplicates} duplicates.") + .replace("{name}", result.bank.name) + .replace("{count}", String(result.bank.questionCount)) + .replace("{items}", String(result.errorItemsCreated)) + .replace("{duplicates}", String(result.duplicates)) + : (t.banks.imported || "Imported {name} with {count} questions.") + .replace("{name}", result.bank.name) + .replace("{count}", String(result.bank.questionCount)); + toast.success(message); + setAddToErrorItems(false); onImported(); } catch (err) { const rawMessage = getApiErrorMessage(err); @@ -98,6 +122,30 @@ export function SharedBankPicker({ existingNames, onImported }: SharedBankPicker

{t.banks.sharedHint}

+
+ + {addToErrorItems && ( + + )} +
{loading ? (