From 850b66e1556e29a1ef716d5cf2014f7c8d5cd63f Mon Sep 17 00:00:00 2001 From: Christ Date: Sat, 15 Aug 2026 12:11:24 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B6=E5=8F=A3=E5=89=8D=E7=AB=AF=E4=B8=9A?= =?UTF-8?q?=E5=8A=A1=E8=BE=B9=E7=95=8C=E4=B8=8E=E9=A2=86=E5=9F=9F=E5=88=86?= =?UTF-8?q?=E6=94=AF=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/architecture/refactoring-master-plan.md | 1 + .../features/accounts/submoduleHooks.test.tsx | 41 +++++++++++++++++++ frontend/app/features/cards/hooks.test.tsx | 29 +++++++++++++ frontend/app/features/chat/state.test.ts | 1 + frontend/app/features/dashboard/state.test.ts | 5 +++ frontend/app/features/items/hooks.test.tsx | 26 ++++++++++++ frontend/app/features/orders/hooks.test.tsx | 14 +++++++ frontend/app/features/settings/hooks.test.tsx | 33 +++++++++++++++ frontend/request.test.ts | 19 +++++++++ 9 files changed, 169 insertions(+) diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index e9fa934..7e3c7a0 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -687,3 +687,4 @@ npm --prefix frontend run build | 2026-08-15 | 完成业务测试覆盖切片“Notifications Hook 定时器、SMTP 与删除边界” | 补充 SMTP 初始加载失败、提示自动消失、弹窗关闭、用户拒绝删除和删除请求失败测试;验证通知状态清理和错误收口,不触发真实推送或邮件服务;前端 Notifications Hook 测试、类型和注释门禁通过 | 下一步:继续补齐 Orders/Items/Settings 等 Hook 的可控生命周期分支 | | 2026-08-15 | 完成业务测试覆盖切片“Orders Hook 查询防抖与辅助错误” | 补充订单主查询失败、搜索文本防抖标准化和账号/商品辅助数据失败测试;验证订单分页状态、请求参数和辅助数据隔离,不依赖真实订单文件或平台数据;前端 Orders Hook 测试、类型和注释门禁通过 | 下一步:继续补齐 Items/Settings 等 Hook 的可控生命周期分支 | | 2026-08-15 | 完成业务测试覆盖切片“Items Hook 批量任务守卫与轮询错误” | 补充无最近任务、无预检、无有效行、用户拒绝取消、不可重试任务和轮询失败测试;验证批量发布状态机前置条件与错误收口,不触发真实商品文件或外部发布平台;前端 Items Hook 测试、类型和注释门禁通过 | 下一步:继续补齐 Settings/Accounts 等 Hook 的可控生命周期分支 | +| 2026-08-15 | 完成阶段性业务覆盖收口切片“请求、账户、卡密、订单与设置边界” | 补充上传超时、批量发布空输入、卡密批量操作空守卫、订单无文件导入、设置外部点击与重载调度、账户绑定移除/AI 默认值/密码终态,以及仪表盘和聊天领域排序时间边界;前端全量 50 个文件、301 个用例通过,语句覆盖率提升至 96.58%、函数 97.25%、行 99.63%;纯 UI 和真实账号/平台流程仍按边界排除 | 下一步:继续处理剩余可控的过期响应、取消清理和领域分支,形成最终业务覆盖率验收清单 | diff --git a/frontend/app/features/accounts/submoduleHooks.test.tsx b/frontend/app/features/accounts/submoduleHooks.test.tsx index 89ac726..0b8d25e 100644 --- a/frontend/app/features/accounts/submoduleHooks.test.tsx +++ b/frontend/app/features/accounts/submoduleHooks.test.tsx @@ -324,4 +324,45 @@ describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知 expect(cancelPasswordMock).toHaveBeenCalledWith('session-1'); hook.unmount(); }); + + test('通知绑定可移除且 AI 默认值与密码登录终态可归一化', /* 当前回调验证账号子模块的派生默认值和终态分支。 */ async () => { + // setEditingAccount 是派生默认值测试的编辑账号状态替身。 + const setEditingAccount = vi.fn(); + // setActiveModal 是派生默认值测试的弹窗状态替身。 + const setActiveModal = vi.fn(); + // setEditForm 是派生默认值测试的表单状态替身。 + const setEditForm = vi.fn(); + // loadAccounts 是派生默认值测试的账号刷新替身。 + const loadAccounts = vi.fn().mockResolvedValue(undefined); + // hook 是通知绑定移除和密码终态场景的 Hook 渲染结果。 + const hook = renderHook( + // derivedHookFactory 创建派生默认值场景的子模块 Hook。 + () => useAccountSubmodules({ editingAccount: accountFixture, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }), + ); + await act( + // editAction 打开编辑弹窗并加载通知绑定。 + async () => hook.result.current.openEditModal(accountFixture), + ); + await act( + // removeBindingAction 移除已经绑定的通知渠道。 + () => hook.result.current.toggleNotificationChannel(1), + ); + expect(hook.result.current.selectedChannelIds).toEqual([]); + + accountAIMock.mockResolvedValueOnce({ ai_enabled: undefined, max_discount_percent: undefined, max_discount_amount: undefined, max_bargain_rounds: undefined, custom_prompts: undefined } as never); + await act( + // defaultAIAction 读取缺少字段的 AI 设置并应用默认值。 + async () => hook.result.current.openAIModal(accountFixture), + ); + expect(hook.result.current.aiSettings).toMatchObject({ ai_enabled: false, max_discount_percent: 10, max_discount_amount: 100, max_bargain_rounds: 3, custom_prompts: '' }); + + passwordLoginMock.mockResolvedValueOnce({ success: true, session_id: 'session-failed', status: 'processing', message: '处理中' }); + passwordStatusMock.mockResolvedValueOnce({ status: 'failed', message: '密码登录失败' }); + await act( + // failedStatusAction 验证密码登录失败终态不再继续轮询。 + async () => hook.result.current.handlePasswordLogin(), + ); + expect(hook.result.current.passwordLoginView).toMatchObject({ status: 'failed', message: '密码登录失败' }); + hook.unmount(); + }); }); diff --git a/frontend/app/features/cards/hooks.test.tsx b/frontend/app/features/cards/hooks.test.tsx index 1f4e2dd..42b5ebb 100644 --- a/frontend/app/features/cards/hooks.test.tsx +++ b/frontend/app/features/cards/hooks.test.tsx @@ -157,4 +157,33 @@ describe('useCardsData 与 useCardBatchActions', /* 当前回调处理卡密库 expect(appendCardMock).toHaveBeenCalledTimes(2); batchHook.unmount(); }); + + test('批量创建和追加的前置条件阻止空操作', /* 当前回调验证卡密批量操作的空输入守卫。 */ async () => { + // hook 是空库存和空输入守卫场景的批量 Hook 渲染结果。 + const hook = renderHook( + // guardHookFactory 创建批量操作守卫场景的 Hook。 + () => useCardBatchActions({ dataCards: [], loadCards: loadCardsFixture }), + ); + await act( + // emptyCreateAction 在没有文件时阻止批量创建。 + async () => hook.result.current.handleBatchCreate(), + ); + expect(batchCreateMock).not.toHaveBeenCalled(); + await act( + // emptyAppendAction 在没有目标和内容时阻止卡密追加。 + async () => hook.result.current.handleBatchAppend(), + ); + expect(appendCardMock).not.toHaveBeenCalled(); + await act( + // emptyRetryAction 在没有上次目标时阻止追加重试。 + async () => hook.result.current.handleRetryBatchAppend(), + ); + expect(appendCardMock).not.toHaveBeenCalled(); + await act( + // openAction 打开空库存批量弹窗并验证目标为空。 + () => hook.result.current.openBatchModal(), + ); + expect(hook.result.current.appendTargetId).toBe(''); + hook.unmount(); + }); }); diff --git a/frontend/app/features/chat/state.test.ts b/frontend/app/features/chat/state.test.ts index f76a68d..cdb1397 100644 --- a/frontend/app/features/chat/state.test.ts +++ b/frontend/app/features/chat/state.test.ts @@ -44,5 +44,6 @@ test('Chat 状态工具覆盖追加消息、搜索字段和时间格式化', expect(isChatAbortError('请求已取消')).toBe(false); expect(formatClock(0)).toBe(''); expect(formatClock(Date.now())).toMatch(/^\d{2}:\d{2}$/); + expect(formatClock(Date.now() - 86_400_000)).toMatch(/\d{2}\/\d{2}/); expect(messageTime(Date.now())).toMatch(/\d{2}\/\d{2}/); }); diff --git a/frontend/app/features/dashboard/state.test.ts b/frontend/app/features/dashboard/state.test.ts index 861c8de..fa90439 100644 --- a/frontend/app/features/dashboard/state.test.ts +++ b/frontend/app/features/dashboard/state.test.ts @@ -34,6 +34,11 @@ test('Dashboard 派生数据覆盖空值、零值和名称截断分支', expect(buildChartData(empty)).toEqual([]); expect(buildChartData({ ...empty, daily_stats: [{ date: '2026-08-15', amount: 0, order_count: 0 }] })).toEqual([{ name: '08-15', amount: 0, orders: 0, avgAmount: 0 }]); expect(buildProductSalesData({ ...analytics, item_stats: [{ ...analytics.item_stats![0], item_id: 'item-long' }] }, { 'item-long': longName })[0].name).toBe('这是一个超过十二个字符的...'); + // rankedAnalytics 是包含多个商品的排行数据,用于覆盖排序比较器。 + const rankedAnalytics = { ...analytics, revenue_stats: { total_amount: 40, total_orders: 4 }, item_stats: [{ item_id: 'item-a', order_count: 1, total_amount: 10, avg_amount: 10 }, { item_id: 'item-b', order_count: 3, total_amount: 30, avg_amount: 10 }] } as OrderAnalytics; + expect(buildProductSalesData(rankedAnalytics, { 'item-a': '商品A', 'item-b': '商品B' })).toEqual([{ name: '商品B', sales: 3 }, { name: '商品A', sales: 1 }]); + expect(buildSourceData(rankedAnalytics, { 'item-a': '商品A', 'item-b': '商品B' }, ['red', 'blue'])[0]).toMatchObject({ name: '商品B', percent: 75, color: 'red' }); + expect(buildCategoryData(rankedAnalytics, { 'item-a': '商品A', 'item-b': '商品B' }, ['blue', 'red'])[0]).toMatchObject({ name: '商品B', percentage: '75.0', color: 'blue' }); expect(buildSourceData(analytics, {}, ['red'])[0]).toMatchObject({ name: 'item-long', percent: 100, color: 'red' }); expect(buildCategoryData(analytics, {}, ['blue'])[0]).toMatchObject({ name: 'item-long', percentage: '100.0', color: 'blue' }); expect(getTrendPercent(null, analytics)).toBeNull(); diff --git a/frontend/app/features/items/hooks.test.tsx b/frontend/app/features/items/hooks.test.tsx index 685af9e..06c27f0 100644 --- a/frontend/app/features/items/hooks.test.tsx +++ b/frontend/app/features/items/hooks.test.tsx @@ -307,6 +307,11 @@ describe('useItemPublishBatch', /* 当前回调处理批量发布的表单、任 test('批量结果和取消重试守卫阻止无效操作', /* 当前回调验证批量发布结果、取消和重试的前置条件。 */ async () => { // hook 是批量操作守卫场景的 Hook 渲染结果。 const hook = renderHook(/* guardHookFactory 创建批量操作守卫场景的 Hook。 */ () => useItemPublishBatch({ selectedAccount: 'account-1', loadItems: vi.fn(), loadShippingRules: vi.fn() })); + await act( + // emptyKeywordAction 在有账号但没有关键词时阻止类目推荐。 + async () => hook.result.current.handleRecommendBatchCategory(), + ); + expect(recommendCategoryMock).not.toHaveBeenCalled(); await act( // emptyRecentAction 在没有最近任务时保持状态稳定。 async () => hook.result.current.openRecentBatchResult(), @@ -317,6 +322,11 @@ describe('useItemPublishBatch', /* 当前回调处理批量发布的表单、任 async () => hook.result.current.handleStartBatch(), ); expect(startBatchMock).not.toHaveBeenCalled(); + await act( + // noDetailCancelAction 在没有任务详情时阻止取消请求。 + async () => hook.result.current.handleCancelBatch(), + ); + expect(cancelBatchMock).not.toHaveBeenCalled(); await act( // invalidPreviewAction 注入没有有效行的预检结果。 () => hook.result.current.setBatchPreview({ ...previewFixture, valid: 0 }), @@ -327,6 +337,22 @@ describe('useItemPublishBatch', /* 当前回调处理批量发布的表单、任 ); expect(startBatchMock).not.toHaveBeenCalled(); expect(alert).toHaveBeenCalledWith('没有可发布的商品行'); + await act( + // noAccountPreviewAction 验证有文件但没有默认账号时阻止预检。 + () => hook.result.current.setBatchFile(new File(['title'], 'items.xlsx')), + ); + // noAccountHook 是没有默认账号的预检 Hook 渲染结果。 + const noAccountHook = renderHook(/* noAccountPreviewHookFactory 创建无账号预检场景的 Hook。 */ () => useItemPublishBatch({ selectedAccount: '', loadItems: vi.fn(), loadShippingRules: vi.fn() })); + await act( + // noAccountFileAction 为无账号预检场景写入文件。 + () => noAccountHook.result.current.setBatchFile(new File(['title'], 'items.xlsx')), + ); + await act( + // noAccountPreviewAction2 触发无默认账号预检守卫。 + async () => noAccountHook.result.current.handlePreviewBatch(), + ); + expect(previewBatchMock).not.toHaveBeenCalled(); + noAccountHook.unmount(); await act( // detailAction 注入可取消的任务详情。 () => hook.result.current.setBatchDetail(runningBatchFixture), diff --git a/frontend/app/features/orders/hooks.test.tsx b/frontend/app/features/orders/hooks.test.tsx index 0f5bd5d..92e512c 100644 --- a/frontend/app/features/orders/hooks.test.tsx +++ b/frontend/app/features/orders/hooks.test.tsx @@ -230,4 +230,18 @@ describe('useOrderQuery 与 useOrderImport', /* 当前回调处理订单查询 hook.unmount(); consoleError.mockRestore(); }); + + test('没有导入文件时不会提交订单导入请求', /* 当前回调验证订单导入提交前置条件。 */ async () => { + // hook 是没有导入文件场景的订单导入 Hook 渲染结果。 + const hook = renderHook( + // emptyImportHookFactory 创建空文件导入场景的 Hook。 + () => useOrderImport(noopLoadOrders), + ); + await act( + // emptyImportAction 在没有文件时触发导入守卫。 + async () => hook.result.current.handleImportOrders(), + ); + expect(importOrdersMock).not.toHaveBeenCalled(); + hook.unmount(); + }); }); diff --git a/frontend/app/features/settings/hooks.test.tsx b/frontend/app/features/settings/hooks.test.tsx index c75e23b..ee4ee32 100644 --- a/frontend/app/features/settings/hooks.test.tsx +++ b/frontend/app/features/settings/hooks.test.tsx @@ -136,6 +136,12 @@ describe('useSettings', /* 当前回调处理系统设置、模型和凭据请 ); expect(hook.result.current.loadError).toBe('设置服务失败'); expect(hook.result.current.settings).toBeNull(); + await act( + // saveGuardAction 在没有配置数据时阻止保存请求。 + async () => hook.result.current.handleSave(), + ); + expect(updateSettingsMock).not.toHaveBeenCalled(); + hook.unmount(); }); test('配置保存和凭据网络异常时保留错误状态', /* 当前回调验证设置保存与凭据网络错误分支。 */ async () => { @@ -171,6 +177,33 @@ describe('useSettings', /* 当前回调处理系统设置、模型和凭据请 async () => hook.result.current.handleCredentialsSave(credentialsEvent), ); expect(hook.result.current.credentialsMessage).toEqual({ type: 'success', text: '更新成功' }); + await waitFor( + // reloadAssertion 等待凭据保存成功后的页面重载调度。 + () => expect(noopReload).toHaveBeenCalled(), + { timeout: 2_000 }, + ); + hook.unmount(); + }); + + test('点击模型选择器外部会关闭下拉框', /* 当前回调验证模型选择器的文档事件边界。 */ async () => { + // hook 是模型选择器外部点击场景的系统设置 Hook 渲染结果。 + const hook = renderHook(renderSettingsHook); + await waitFor( + // statusAssertion 等待设置加载完成后再操作下拉框。 + () => expect(hook.result.current.requestStatus).toBe('success'), + ); + // picker 是模型选择器根节点替身。 + const picker = document.createElement('div'); + hook.result.current.modelPickerRef.current = picker; + await act( + // openAction 打开模型下拉框。 + () => hook.result.current.setModelDropdownOpen(true), + ); + document.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); + await waitFor( + // closeAssertion 等待外部点击关闭下拉框。 + () => expect(hook.result.current.modelDropdownOpen).toBe(false), + ); hook.unmount(); }); }); diff --git a/frontend/request.test.ts b/frontend/request.test.ts index 8be0af5..f0f93c3 100644 --- a/frontend/request.test.ts +++ b/frontend/request.test.ts @@ -166,6 +166,25 @@ describe('request helpers', () => { vi.useRealTimers(); } /* 回调函数负责当前业务流程。 */); + test('上传请求超时后返回上传专用错误', /* 当前回调验证上传请求的超时错误分支。 */ async () => { + vi.useFakeTimers(); + try { + // fetchMock 是等待上传超时信号的网络替身。 + const fetchMock = vi.fn(/* uploadTimeoutFactory 创建等待上传超时的网络替身。 */ (_url: string, init: RequestInit) => new Promise(/* uploadTimeoutExecutor 等待上传控制器超时。 */ (_resolve, reject) => { + init.signal?.addEventListener('abort', /* abortCallback 将上传超时转换为网络异常。 */ () => reject(new DOMException('timeout', 'AbortError')), { once: true }); + })); + vi.stubGlobal('fetch', fetchMock); + // pending 是等待上传超时结果的请求 Promise。 + const pending = postForm('/slow-upload', new FormData(), { timeoutMs: 50 }); + // rejection 是断言上传超时错误的异步结果。 + const rejection = expect(pending).rejects.toThrow('上传超时'); + await vi.advanceTimersByTimeAsync(50); + await rejection; + } finally { + vi.useRealTimers(); + } + } /* 回调函数负责当前业务流程。 */); + test('外部 AbortSignal 取消请求时返回取消错误', async () => { // controller 是调用方主动取消请求的控制器。 const controller = new AbortController();