补齐账号聊天轮询与过期边界测试

This commit is contained in:
Christ committed 2026-08-15 12:20:11 +08:00
1 parent 850b66e155
commit 6b5215ddf3
6 files changed
+187 -3

No files matched your search

@@ -688,3 +688,4 @@ npm --prefix frontend run build
| 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 和真实账号/平台流程仍按边界排除 | 下一步:继续处理剩余可控的过期响应、取消清理和领域分支,形成最终业务覆盖率验收清单 |
| 2026-08-15 | 完成业务测试覆盖切片“账号任务、账号轮询与聊天实时边界” | 补充账号任务保存并发门禁、账号运行状态下一轮定时轮询、通知绑定移除/暂停状态更新、密码登录处理中轮询与关闭清理、聊天空发送/滚动守卫/未知会话排序,以及规则分页兼容入口测试;前端注释门禁、定向测试和类型检查通过,阶段覆盖率提升至语句 97.49%、函数 99.08%、行 99.86%;过期响应保护仍按真实取消时序分类保留 | 下一步:继续评估通知、卡密、设置与请求层过期响应是否能在不引入不稳定时序的前提下补测 |
@@ -83,6 +83,7 @@ describe('useAccountAutomation', /* 当前回调处理账号任务 Hook 的请
);
expect(updateSettingsMock).toHaveBeenCalledTimes(2);
expect(hook.result.current.error).toBe('');
hook.unmount();
});
test('禁用账号不会发起立即执行请求', /* 当前回调验证账号运行门禁。 */ async () => {
@@ -101,6 +102,7 @@ describe('useAccountAutomation', /* 当前回调处理账号任务 Hook 的请
async () => hook.result.current.run('auto_rate'),
);
expect(runTaskMock).not.toHaveBeenCalled();
hook.unmount();
});
test('加载设置失败时展示业务错误', /* 当前回调验证首次读取失败分支。 */ async () => {
@@ -112,6 +114,7 @@ describe('useAccountAutomation', /* 当前回调处理账号任务 Hook 的请
() => expect(hook.result.current.loading).toBe(false),
);
expect(hook.result.current.error).toBe('读取失败');
hook.unmount();
});
test('执行失败后可通过 retry 重试', /* 当前回调验证执行失败与重试动作。 */ async () => {
@@ -134,5 +137,37 @@ describe('useAccountAutomation', /* 当前回调处理账号任务 Hook 的请
);
expect(runTaskMock).toHaveBeenCalledTimes(2);
expect(hook.result.current.error).toBe('');
hook.unmount();
});
test('保存进行中时忽略重复保存动作', /* 当前回调验证账号任务保存的并发门禁。 */ async () => {
// resolveUpdate 是延迟保存请求的完成控制器。
let resolveUpdate: (value: AccountTaskSettingsResponse) => void = () => undefined;
// pendingUpdate 是保持 saving 状态的保存请求 Promise。
const pendingUpdate = new Promise<AccountTaskSettingsResponse>(/* updateExecutor 保存延迟 Promise 的完成函数。 */ resolve => { resolveUpdate = resolve; });
updateSettingsMock.mockReturnValueOnce(pendingUpdate);
// hook 是保存并发门禁场景的账号任务 Hook 渲染结果。
const hook = renderHook(renderAutomationHook);
await waitFor(
// loadingAssertion 等待任务设置初始加载完成。
() => expect(hook.result.current.loading).toBe(false),
);
// firstSave 是保持进行中的首次保存动作。
const firstSave = hook.result.current.save();
await waitFor(
// savingAssertion 等待保存状态打开。
() => expect(hook.result.current.saving).toBe(true),
);
await act(
// duplicateSaveAction 触发重复保存并验证门禁。
async () => hook.result.current.save(),
);
expect(updateSettingsMock).toHaveBeenCalledTimes(1);
resolveUpdate(settingsFixture);
await act(
// resolveAction 完成首次保存请求并收口状态。
async () => firstSave,
);
hook.unmount();
});
});
@@ -1,5 +1,6 @@
// @vitest-environment jsdom
import { renderHook, waitFor } from '@testing-library/react';
import { act } from 'react';
import { beforeEach, describe, expect, test, vi } from 'vitest';
import type { AccountDetail } from '../../../types';
import { getAccountDetails, getAccountRuntimeStatuses, getAllAISettings } from './api';
@@ -96,4 +97,27 @@ describe('useAccountsData', /* 当前回调处理账号详情、AI 配置和运
expect(console.error).toHaveBeenCalledWith('加载账号运行状态失败:', expect.any(Error));
hook.unmount();
});
test('运行状态轮询完成后按计划安排下一轮查询', /* 当前回调验证账号状态轮询定时器回调。 */ async () => {
vi.useFakeTimers();
try {
// hook 是账号轮询定时器场景的 Hook 渲染结果。
const hook = renderHook(
// timerHookFactory 创建账号轮询定时器场景的 Hook。
() => useAccountsData(),
);
await act(
// initialFlushAction 刷新初始账号和运行状态 Promise。
async () => { await Promise.resolve(); await Promise.resolve(); },
);
await act(
// timerAction 推进两秒轮询定时器。
async () => { await vi.advanceTimersByTimeAsync(2_000); },
);
expect(getRuntimeMock).toHaveBeenCalledTimes(2);
hook.unmount();
} finally {
vi.useRealTimers();
}
});
});
@@ -133,6 +133,16 @@ describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知
async () => hook.result.current.handleRestartPause(),
);
expect(pauseMock).toHaveBeenCalledWith('account-1', 60);
// pauseUpdater 是暂停成功后写回编辑账号状态的函数式更新器。
let pauseUpdater: ((current: AccountDetail | null) => AccountDetail | null) | undefined;
for (const call /* call 是编辑账号状态替身记录的一次调用参数。 */ of setEditingAccount.mock.calls) {
if (typeof call[0] === 'function') {
pauseUpdater = call[0] as (current: AccountDetail | null) => AccountDetail | null;
break;
}
}
expect(pauseUpdater?.(accountFixture)).toMatchObject({ pause_duration: 60, paused: true, paused_until: 12345 });
expect(pauseUpdater?.(null)).toBeNull();
setLongLoginMock.mockRejectedValueOnce(new Error('长登录保存失败'));
await act(
@@ -298,6 +308,7 @@ describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知
});
test('密码登录处理中和失败状态都能关闭会话', /* 当前回调验证密码登录中间状态与关闭清理。 */ async () => {
vi.useFakeTimers();
// setEditingAccount 是密码登录中间状态的账号状态替身。
const setEditingAccount = vi.fn();
// setActiveModal 是密码登录中间状态的弹窗状态替身。
@@ -317,12 +328,24 @@ describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知
async () => hook.result.current.handlePasswordLogin(),
);
expect(hook.result.current.passwordLoginView.status).toBe('processing');
await act(
// pollTimerAction 推进密码登录状态轮询定时器。
async () => { await vi.advanceTimersByTimeAsync(1_500); },
);
expect(hook.result.current.passwordLoginView.status).toBe('success');
passwordLoginMock.mockResolvedValueOnce({ success: true, session_id: 'session-2', status: 'processing', message: '处理中' });
passwordStatusMock.mockResolvedValueOnce({ status: 'processing', message: '处理中' });
await act(
// secondProcessingAction 再次进入处理中状态以验证关闭时取消会话。
async () => hook.result.current.handlePasswordLogin(),
);
await act(
// closeAction 关闭编辑弹窗并取消处理中会话。
async () => hook.result.current.closeEditModal(),
);
expect(cancelPasswordMock).toHaveBeenCalledWith('session-1');
expect(cancelPasswordMock).toHaveBeenCalledWith('session-2');
hook.unmount();
vi.useRealTimers();
});
test('通知绑定可移除且 AI 默认值与密码登录终态可归一化', /* 当前回调验证账号子模块的派生默认值和终态分支。 */ async () => {
@@ -365,4 +388,46 @@ describe('useAccountSubmodules', /* 当前回调处理账号编辑、AI、通知
expect(hook.result.current.passwordLoginView).toMatchObject({ status: 'failed', message: '密码登录失败' });
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(
// emptyAccountHookFactory 创建空编辑账号场景的子模块 Hook。
() => useAccountSubmodules({ editingAccount: null, setEditingAccount, setActiveModal, editForm: editFormFixture, setEditForm, loadAccounts }),
);
await act(
// longLoginGuardAction 阻止空账号长期登录操作。
async () => hook.result.current.handleLongLoginToggle(),
);
await act(
// aiGuardAction 阻止空账号 AI 保存操作。
async () => hook.result.current.handleSaveAISettings(),
);
await act(
// editGuardAction 阻止空账号编辑保存操作。
async () => hook.result.current.handleSaveEdit(),
);
await act(
// pauseGuardAction 阻止空账号暂停操作。
async () => hook.result.current.handleRestartPause(),
);
await act(
// passwordGuardAction 阻止空账号密码登录操作。
async () => hook.result.current.handlePasswordLogin(),
);
expect(setLongLoginMock).not.toHaveBeenCalled();
expect(updateAIMock).not.toHaveBeenCalled();
expect(updateAccountMock).not.toHaveBeenCalled();
expect(pauseMock).not.toHaveBeenCalled();
expect(passwordLoginMock).not.toHaveBeenCalled();
hook.unmount();
});
});
+40 -1
View File
@@ -100,6 +100,11 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
expect(hook.result.current.activeChatID).toBe('chat-1');
expect(hook.result.current.messages).toEqual([messageFixture]);
expect(markReadMock).toHaveBeenCalledWith('account-1', 'chat-1', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(hook.result.current.unreadForAccount('account-1')).toBe(0);
await act(
// emptySendAction 在没有草稿时阻止文字发送。
async () => hook.result.current.handleSend(),
);
await act(
// draftAction 写入文字消息草稿。
@@ -117,6 +122,24 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
async () => hook.result.current.handleImage(new File(['image'], 'image.png', { type: 'image/png' })),
);
expect(sendImageMock).toHaveBeenCalledWith(expect.objectContaining({ chat_id: 'chat-1', image: expect.any(File) }), expect.objectContaining({ signal: expect.any(AbortSignal) }));
// imageInput 是图片发送成功后需要清空的输入框替身。
const imageInput = { value: 'selected-file' } as HTMLInputElement;
hook.result.current.imageInputRef.current = imageInput;
await act(
// secondImageAction 再次发送图片以验证输入框清理。
async () => hook.result.current.handleImage(new File(['image'], 'second.png', { type: 'image/png' })),
);
expect(imageInput.value).toBe('');
await act(
// emptyImageAction 在没有图片文件时阻止发送。
async () => hook.result.current.handleImage(),
);
// emptyScrollAction 在没有滚动容器时保持滚动策略稳定。
hook.result.current.scrollRef.current = null;
await act(
// nullScrollAction 验证滚动容器缺失守卫。
() => hook.result.current.handleMessageScroll(),
);
hook.unmount();
});
@@ -169,6 +192,9 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
});
test('WebSocket 连接和消息事件更新聊天状态', /* 当前回调验证实时连接和消息回调边界。 */ async () => {
// secondSession 是用于覆盖实时会话排序比较器的第二条会话。
const secondSession = { ...sessionFixture, chat_id: 'chat-2', last_message_at: 2, unread_count: 0 };
getSessionPageMock.mockResolvedValue({ sessions: [sessionFixture, secondSession], has_more: true, next_cursor: 2 });
// hook 是实时连接场景的聊天 Hook 渲染结果。
const hook = renderHook(
// socketHookFactory 创建实时连接场景的聊天 Hook。
@@ -311,8 +337,11 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
try {
// initialStatus 是初始化请求返回的运行状态。
const initialStatus = { 'account-1': { state: 'online' as const, connected: true, failures: 0, updated_at: '2026-08-15T00:00:00Z' } };
// refreshedStatus 是首次轮询返回的更新状态。
const refreshedStatus = { 'account-1': { state: 'reconnecting' as const, connected: false, failures: 1, updated_at: '2026-08-15T00:00:01Z' } };
getRuntimeMock.mockReset();
getRuntimeMock.mockResolvedValueOnce(initialStatus);
getRuntimeMock.mockResolvedValueOnce(refreshedStatus);
getRuntimeMock.mockRejectedValueOnce(new Error('轮询失败'));
// hook 是轮询失败场景的聊天 Hook 渲染结果。
const hook = renderHook(
@@ -327,7 +356,12 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
// pollingTimerAction 推进首次轮询定时器。
async () => { await vi.advanceTimersByTimeAsync(3_000); },
);
expect(getRuntimeMock).toHaveBeenCalledTimes(2);
expect(hook.result.current.accounts[0]?.runtime_state).toBe('reconnecting');
await act(
// retryPollingTimerAction 推进失败后的下一次轮询定时器。
async () => { await vi.advanceTimersByTimeAsync(3_000); },
);
expect(getRuntimeMock).toHaveBeenCalledTimes(3);
hook.unmount();
} finally {
vi.useRealTimers();
@@ -367,6 +401,11 @@ describe('useChat', /* 当前回调处理聊天加载、分页、发送和实时
);
expect(hook.result.current.messages).toEqual([olderMessage, messageFixture]);
expect(container.scrollTop).toBe(80);
await act(
// noOlderAction 在没有更多历史消息时阻止重复分页请求。
async () => hook.result.current.loadOlderMessages(),
);
expect(getMessagePageMock).toHaveBeenCalledTimes(2);
// unknownMessage 是不在当前联系人列表中的实时消息。
const unknownMessage = { ...messageFixture, chat_id: 'chat-unknown', message_key: 'message-unknown', content: '未知会话消息' };
+21 -1
View File
@@ -11,7 +11,7 @@ import {
getReplyRules,
getShippingRulesPage,
} from './api';
import { useRulesData } from './hooks';
import { useRulesData, useRulesDataWithPageChange } from './hooks';
vi.mock('./api', /* rulesApiMockFactory 提供规则数据 Hook 的确定性 API 替身。 */ () => ({
getAccountDetails: vi.fn(),
@@ -83,6 +83,10 @@ describe('useRulesData', /* 当前回调处理规则页参考数据、分页和
expect(hook.result.current.accounts).toEqual([accountFixture]);
expect(hook.result.current.cards).toEqual([cardFixture]);
expect(setSelectedAccountId).toHaveBeenCalled();
// selectedAccountUpdater 是规则 Hook 回填账号时交给 React 的函数式更新器。
const selectedAccountUpdater = setSelectedAccountId.mock.calls[0][0] as (current: string) => string;
expect(selectedAccountUpdater('')).toBe('account-1');
expect(selectedAccountUpdater('existing')).toBe('existing');
await act(
// automationAction 加载分页规则和异常。
async () => hook.result.current.loadAutomationRules(),
@@ -163,4 +167,20 @@ describe('useRulesData', /* 当前回调处理规则页参考数据、分页和
expect(setSelectedAccountId).toHaveBeenCalledWith(expect.any(Function));
hook.unmount();
});
test('带分页回调的规则 Hook 入口保持数据契约', /* 当前回调验证分页兼容入口委托到统一规则 Hook。 */ async () => {
// setSelectedAccountId 是分页兼容入口所需的账号状态替身。
const setSelectedAccountId = vi.fn();
// hook 是分页兼容入口的规则数据 Hook 渲染结果。
const hook = renderHook(
// pageChangeHookFactory 创建带分页回调的规则 Hook。
() => useRulesDataWithPageChange({ activeTab: 'automation', selectedAccountId: 'account-1', automationTriggerFilter: '', automationStatusFilter: 'all', debouncedAutomationSearch: '', automationPage: 1, automationPageSize: 10, setSelectedAccountId }),
);
await act(
// refreshAction 通过兼容入口刷新规则数据。
async () => hook.result.current.refresh(),
);
expect(hook.result.current.automationRules).toEqual([shippingFixture]);
hook.unmount();
});
});