补齐账号任务与仪表盘Hook测试
This commit is contained in:
1 parent
6116428bf6
commit
82d76f9fcc
5 files changed
+923
No files matched your search
@@ -0,0 +1,105 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { AccountDetail, AccountTaskSettingsResponse } from '../../../types';
|
||||
import { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './api';
|
||||
import { useAccountAutomation } from './hooks';
|
||||
|
||||
vi.mock('./api', /* apiMockFactory 提供账号任务 Hook 的确定性 API 替身。 */ () => ({
|
||||
getAccountTaskSettings: vi.fn(),
|
||||
runAccountTask: vi.fn(),
|
||||
updateAccountTaskSettings: vi.fn(),
|
||||
}));
|
||||
|
||||
// getSettingsMock 是读取账号任务设置的可控请求替身。
|
||||
const getSettingsMock = vi.mocked(getAccountTaskSettings);
|
||||
// runTaskMock 是立即执行账号任务的可控请求替身。
|
||||
const runTaskMock = vi.mocked(runAccountTask);
|
||||
// updateSettingsMock 是保存账号任务设置的可控请求替身。
|
||||
const updateSettingsMock = vi.mocked(updateAccountTaskSettings);
|
||||
|
||||
// accountFixture 是 Hook 测试使用的启用账号对象。
|
||||
const accountFixture: AccountDetail = { id: 'account-1', enabled: true, auto_confirm: false, auto_rate_enabled: true, rate_content: '交易愉快', auto_polish_enabled: false, polish_time: '03:00' };
|
||||
|
||||
// settingsFixture 是账号任务接口返回的完整设置对象。
|
||||
const settingsFixture: AccountTaskSettingsResponse = { account_id: 'account-1', auto_rate_enabled: true, rate_content: '已保存文案', auto_polish_enabled: true, polish_time: '04:00', last_rate_scan_at: 0, last_polish_date: '', last_polish_at: 0 };
|
||||
|
||||
// onSavedFixture 是保存或执行成功后的页面同步回调替身。
|
||||
const onSavedFixture = vi.fn();
|
||||
|
||||
// renderAutomationHook 是渲染账号任务 Hook 的具名回调。
|
||||
const renderAutomationHook = () => useAccountAutomation({ account: accountFixture, onSaved: onSavedFixture });
|
||||
|
||||
describe('useAccountAutomation', /* 当前回调处理账号任务 Hook 的请求与动作状态。 */ () => {
|
||||
beforeEach(/* 当前回调重置所有 API 替身和页面回调。 */ () => {
|
||||
vi.clearAllMocks();
|
||||
getSettingsMock.mockResolvedValue(settingsFixture);
|
||||
updateSettingsMock.mockResolvedValue(settingsFixture);
|
||||
runTaskMock.mockResolvedValue({ success: true, summary: { task_type: 'auto_rate', found: 1, success: 1, failed: 0, skipped: 0 } });
|
||||
});
|
||||
|
||||
test('加载设置后可以保存和立即执行任务', /* 当前回调验证成功加载、保存和执行路径。 */ async () => {
|
||||
// hook 是账号任务 Hook 的渲染结果。
|
||||
const hook = renderHook(renderAutomationHook);
|
||||
await waitFor(
|
||||
// loadingAssertion 等待首次设置请求完成。
|
||||
() => expect(hook.result.current.loading).toBe(false),
|
||||
);
|
||||
expect(hook.result.current.form).toEqual(settingsFixture);
|
||||
|
||||
await act(
|
||||
// saveAction 执行设置保存动作。
|
||||
async () => hook.result.current.save(),
|
||||
);
|
||||
expect(updateSettingsMock).toHaveBeenCalledWith('account-1', settingsFixture, expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(onSavedFixture).toHaveBeenCalledWith(settingsFixture);
|
||||
|
||||
await act(
|
||||
// runAction 执行自动擦亮任务。
|
||||
async () => hook.result.current.run('auto_polish'),
|
||||
);
|
||||
expect(runTaskMock).toHaveBeenCalledWith('account-1', 'auto_polish', expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
||||
expect(hook.result.current.summary).toMatchObject({ success: 1 });
|
||||
expect(hook.result.current.error).toBe('');
|
||||
});
|
||||
|
||||
test('保存失败后可通过 retry 重试并清除错误', /* 当前回调验证失败状态和安全重试路径。 */ async () => {
|
||||
// hook 是保存失败场景下的账号任务 Hook 渲染结果。
|
||||
const hook = renderHook(renderAutomationHook);
|
||||
await waitFor(
|
||||
// loadingAssertion 等待失败场景的首次设置请求完成。
|
||||
() => expect(hook.result.current.loading).toBe(false),
|
||||
);
|
||||
updateSettingsMock.mockRejectedValueOnce(new Error('保存失败'));
|
||||
await act(
|
||||
// saveAction 执行预期失败的设置保存动作。
|
||||
async () => hook.result.current.save(),
|
||||
);
|
||||
expect(hook.result.current.error).toBe('保存失败');
|
||||
expect(hook.result.current.retryAvailable).toBe(true);
|
||||
await act(
|
||||
// retryAction 触发最近一次保存动作的重试。
|
||||
async () => hook.result.current.retry(),
|
||||
);
|
||||
expect(updateSettingsMock).toHaveBeenCalledTimes(2);
|
||||
expect(hook.result.current.error).toBe('');
|
||||
});
|
||||
|
||||
test('禁用账号不会发起立即执行请求', /* 当前回调验证账号运行门禁。 */ async () => {
|
||||
// disabledAccount 是不允许执行账号级计划任务的账号对象。
|
||||
const disabledAccount = { ...accountFixture, enabled: false };
|
||||
// renderDisabledHook 是禁用账号 Hook 的渲染回调。
|
||||
const renderDisabledHook = () => useAccountAutomation({ account: disabledAccount, onSaved: onSavedFixture });
|
||||
// hook 是禁用账号 Hook 的渲染结果。
|
||||
const hook = renderHook(renderDisabledHook);
|
||||
await waitFor(
|
||||
// loadingAssertion 等待禁用账号的设置读取完成。
|
||||
() => expect(hook.result.current.loading).toBe(false),
|
||||
);
|
||||
await act(
|
||||
// runAction 验证禁用账号不会提交自动评价任务。
|
||||
async () => hook.result.current.run('auto_rate'),
|
||||
);
|
||||
expect(runTaskMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest';
|
||||
import type { DashboardStats, Item, OrderAnalyticsResponse } from '../../../types';
|
||||
import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from './api';
|
||||
import { useDashboard } from './hooks';
|
||||
import type { UseDashboardOptions } from './hooks';
|
||||
|
||||
vi.mock('./api', /* dashboardApiMockFactory 提供仪表盘 Hook 的确定性 API 替身。 */ () => ({
|
||||
getDashboardStats: vi.fn(),
|
||||
getItems: vi.fn(),
|
||||
getOrderAnalytics: vi.fn(),
|
||||
getValidOrders: vi.fn(),
|
||||
}));
|
||||
|
||||
// getStatsMock 是读取仪表盘概览统计的可控请求替身。
|
||||
const getStatsMock = vi.mocked(getDashboardStats);
|
||||
// getItemsMock 是读取商品列表的可控请求替身。
|
||||
const getItemsMock = vi.mocked(getItems);
|
||||
// getAnalyticsMock 是读取订单分析数据的可控请求替身。
|
||||
const getAnalyticsMock = vi.mocked(getOrderAnalytics);
|
||||
// getValidOrdersMock 是读取有效订单的可控请求替身。
|
||||
const getValidOrdersMock = vi.mocked(getValidOrders);
|
||||
|
||||
// statsFixture 是仪表盘概览统计测试数据。
|
||||
const statsFixture: DashboardStats = { total_cookies: 2, active_cookies: 1, total_cards: 3, total_keywords: 4, total_orders: 5, available_card_stock: 6 };
|
||||
// itemsFixture 是用于建立商品名称索引的测试数据。
|
||||
const itemsFixture: Item[] = [{ id: 'item-1', cookie_id: 'account-1', item_id: 'item-1', item_title: '测试商品' }];
|
||||
// analyticsFixture 是覆盖趋势图和商品排行的分析数据。
|
||||
const analyticsFixture: OrderAnalyticsResponse = { revenue_stats: { total_amount: 100, total_orders: 2, avg_amount: 50, unique_buyers: 2, unique_items: 1 }, daily_stats: [{ date: '2026-08-15', amount: 100, order_count: 2 }], status_stats: [], city_stats: [], item_stats: [{ item_id: 'item-1', order_count: 2, total_amount: 100, avg_amount: 50 }] };
|
||||
// validOrdersFixture 是有效订单查询的最小返回结果。
|
||||
const validOrdersFixture = { orders: [], total: 0, truncated: false };
|
||||
// dashboardOptions 是今天范围的仪表盘 Hook 参数。
|
||||
const dashboardOptions: UseDashboardOptions = { range: 'today', customStartDate: '', customEndDate: '', customRangeVersion: 0 };
|
||||
|
||||
// renderDashboardHook 是渲染仪表盘 Hook 的具名回调。
|
||||
const renderDashboardHook = () => useDashboard(dashboardOptions);
|
||||
|
||||
describe('useDashboard', /* 当前回调处理仪表盘并行请求和派生数据状态。 */ () => {
|
||||
beforeEach(/* 当前回调重置仪表盘 API 替身。 */ () => {
|
||||
vi.clearAllMocks();
|
||||
getStatsMock.mockResolvedValue(statsFixture);
|
||||
getItemsMock.mockResolvedValue(itemsFixture);
|
||||
getAnalyticsMock.mockResolvedValue(analyticsFixture);
|
||||
getValidOrdersMock.mockResolvedValue(validOrdersFixture);
|
||||
});
|
||||
|
||||
test('并行加载概览和时间范围数据后生成派生结果', /* 当前回调验证仪表盘成功加载路径。 */ async () => {
|
||||
// hook 是仪表盘 Hook 的渲染结果。
|
||||
const hook = renderHook(renderDashboardHook);
|
||||
await waitFor(
|
||||
// overviewAssertion 等待概览请求成功。
|
||||
() => expect(hook.result.current.status.overview).toBe('success'),
|
||||
);
|
||||
await waitFor(
|
||||
// rangeAssertion 等待时间范围请求成功。
|
||||
() => expect(hook.result.current.status.range).toBe('success'),
|
||||
);
|
||||
expect(hook.result.current.data).toMatchObject({ stats: statsFixture, items: itemsFixture, itemNames: { 'item-1': '测试商品' } });
|
||||
expect(hook.result.current.chartData[0]).toMatchObject({ name: '08-15', orders: 2 });
|
||||
expect(hook.result.current.productSalesData).toEqual([{ name: '测试商品', sales: 2 }]);
|
||||
expect(hook.result.current.selectedRangeLabel).toBe('今天');
|
||||
expect(hook.result.current.maxProductSales).toBe(2);
|
||||
expect(getAnalyticsMock).toHaveBeenCalledTimes(2);
|
||||
expect(getValidOrdersMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
await act(
|
||||
// refreshAction 触发概览和范围数据重新加载。
|
||||
async () => hook.result.current.refresh(),
|
||||
);
|
||||
await waitFor(
|
||||
// refreshAssertion 等待刷新后的概览请求发出。
|
||||
() => expect(getStatsMock).toHaveBeenCalledTimes(2),
|
||||
);
|
||||
});
|
||||
|
||||
test('概览请求失败时展示错误状态并保留范围请求', /* 当前回调验证概览错误分支。 */ async () => {
|
||||
getStatsMock.mockRejectedValueOnce(new Error('概览服务失败'));
|
||||
// hook 是概览请求失败场景下的仪表盘 Hook 渲染结果。
|
||||
const hook = renderHook(renderDashboardHook);
|
||||
await waitFor(
|
||||
// errorAssertion 等待概览错误状态写入。
|
||||
() => expect(hook.result.current.status.overview).toBe('error'),
|
||||
);
|
||||
expect(hook.result.current.status.error).toBe('概览服务失败');
|
||||
await waitFor(
|
||||
// rangeAssertion 等待概览失败时仍完成的范围请求。
|
||||
() => expect(hook.result.current.status.range).toBe('success'),
|
||||
);
|
||||
});
|
||||
|
||||
test('自定义日期倒置时阻断范围请求并提示错误', /* 当前回调验证日期范围校验错误分支。 */ async () => {
|
||||
// invalidOptions 是开始日期晚于结束日期的非法范围参数。
|
||||
const invalidOptions: UseDashboardOptions = { range: 'custom', customStartDate: '2026-08-20', customEndDate: '2026-08-01', customRangeVersion: 1 };
|
||||
// renderInvalidHook 是非法日期范围 Hook 的渲染回调。
|
||||
const renderInvalidHook = () => useDashboard(invalidOptions);
|
||||
// hook 是非法日期范围 Hook 的渲染结果。
|
||||
const hook = renderHook(renderInvalidHook);
|
||||
await waitFor(
|
||||
// rangeAssertion 等待日期范围错误状态写入。
|
||||
() => expect(hook.result.current.status.range).toBe('error'),
|
||||
);
|
||||
expect(hook.result.current.status.error).toBe('开始日期不能晚于结束日期');
|
||||
expect(getAnalyticsMock).not.toHaveBeenCalled();
|
||||
expect(getValidOrdersMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user