Files
crawler-plugin/frontend-vue/tests/mount/jd-collect-progress.mount.test.ts
T
huangzd1997 10dec12ec0 refactor(前端): 前后台界面小字全面精简——删技术ID括号/页头操作提示条/机制解释句(2026-11-28 客户口径「这些小字都不需要多余,还有shopId啥的…除了必须要的比如任务ID密钥,其他精简一些」)
用户端 frontend-vue:
- jd-publish-shop.ts:shopLabel 只出店名(缺名兜底「店铺 N」),跨店/多店琥珀文案压成一两句,判据逻辑零改动
- JdPublishTab:删工具头/分类解释/品牌句后半,默认店铺/选品/collect-hint/中断回执/加价规则各压一句
- JdCollectTab:删工具头 desc、分类机制句、断点游标行,「页面筛选未生效兜底翻页中」从任务卡撤下
- jd-on-shelf 空态一句、JdConsolePage hero-sub 整段删(含过时的「正在建设中」)
- 品牌 10 个 tab:输入/筛选/加载长句压一句或删,任务卡删「结果ID/店铺ID/平台」技术行(店名已显形)
- 保留:错误出口、额度「当前在架X/Y」、GROUPS_EMPTY 空态动作句、检测按钮与店铺显形

后管 admin-frontend-vue:
- 每页顶部「当前页面操作提示」条整条下线(删 OperationGuide.vue+operation-guides.ts)
- 撞款/任务中心/关键词用量/密钥用量/客户端包/教程/软件版本/数字人/菜单/店铺密钥/登录页逐页删说明小字(保留:踢线警示、「留空=永不过期」、「不要带v前缀」、「仅支持.zip」、草稿需手动发布、已授权人数、安全提示)
- 编辑/建号弹窗 label 括号收短;代理弹窗/设备日志(删 pywebview/kk-browser 进程名)/密钥 pill title/授权弹窗 dim/品牌门控空态收短

测试同步(16 支改反钉或同步断言,全部当场绿):
- align-operation-guide 整份重写为反钉(组件与文案表不得回流)
- source-pin 台账 task-center-board 条目手工点名 7/3/5→24/14/28:旧值是切分器把正则字面量内裸引号当字符串开关吞掉 18 支用例的误量(stripNonCode 不识别 regex literal),本次改写恰好移除该文件最后两处带引号正则后测出真值;真实用例数反而 25→24(删 1 支 guide 用例),非真实增长

门禁:后管 node --test 1965/1965+vitest 253/253+vue-tsc rc=0;用户端 node 1150/mount 149/vue-tsc rc=0;ops 快检 --fast overall=pass(后端9.5/后管8.8/客户端9.8/用户端9.6)。本窗不发版;app_client/jar/后端零改动。
2026-11-28 01:14:51 +08:00

663 lines
30 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 「获取店铺数据」一键采集 + 任务面板挂载用例(v1.5 改版后)。
*
* 页面改版(2026-11-15):左侧只留「一键获取店铺数据」按钮,右侧换共享任务面板
* (TaskCenterPanel + useLiveTaskBoard,与外观专利同一骨架);单任务进度条移除,
* 进度在任务卡片上。四组靶子保留,缺一条就是假绿:
* ① 点一次按钮就走完整链路:建单 → 激活 → 把 `jd-shop-collect-run` 推进本机客户端队列 → 轮询批量进度;
* ② 有 total 时卡片进度条按已落库商品数算出真实百分比(分母只来自服务端游标,不编造);
* ③ total 缺失时只显示「已采集 N 个商品」,不编造百分比;
* ④ 终态即收手:SUCCESS/FAILED 从轮询移除,FAILED 显示服务端原因并出「重试」按钮
* (重试走通用原位复位 + 重新激活推队列——断点续传,不新建任务)。
*
* 跑法:`npx vitest run tests/mount/jd-collect-progress.mount.test.ts`
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ElementPlus, { ElOption, ElSelect } from 'element-plus'
import JdCollectTab from '@/pages/jd/JdCollectTab.vue'
import { resetJdLoginAutoflowForTest } from '@/shared/stores/jd-login-autoflow'
const api = vi.hoisted(() => ({
createJdCollectTask: vi.fn(),
// 8d8c88a5 起建单后先 PENDING→RUNNING 再推队列;mock 里缺这一个键会让组件拿到
// undefined 调用、enqueue 永远不被调用(本文件当时没跟上,红在这里)。
activateJdCollectTask: vi.fn(),
fetchJdCollectCategories: vi.fn(),
fetchJdCollectGroups: vi.fn(),
fetchJdCollectDashboard: vi.fn(),
fetchJdCollectHistory: vi.fn(),
fetchJdCollectTaskProgressBatch: vi.fn(),
deleteJdCollectTask: vi.fn(),
interruptJdCollectTask: vi.fn(),
retryClientTask: vi.fn(),
enqueue: vi.fn(),
// 2026-11-19「同步分类」:选项集正本从冻结快照改为桥实时拉取(每家店的店内分类不同)。
syncCategories: vi.fn(),
// 2026-11-23「登录京麦」按钮退役:jd_login 自动开登录窗走桥 open_jd_login(autoflow 闸)。
openJdLogin: vi.fn(),
}))
vi.mock('@/shared/api/types/modules/jd-collect', () => ({
createJdCollectTask: api.createJdCollectTask,
activateJdCollectTask: api.activateJdCollectTask,
fetchJdCollectCategories: api.fetchJdCollectCategories,
fetchJdCollectGroups: api.fetchJdCollectGroups,
fetchJdCollectProgress: vi.fn(),
fetchJdCollectDashboard: api.fetchJdCollectDashboard,
fetchJdCollectHistory: api.fetchJdCollectHistory,
fetchJdCollectTaskProgressBatch: api.fetchJdCollectTaskProgressBatch,
deleteJdCollectTask: api.deleteJdCollectTask,
interruptJdCollectTask: api.interruptJdCollectTask,
}))
vi.mock('@/shared/api/task-retry', () => ({
retryClientTask: api.retryClientTask,
}))
vi.mock('@/shared/bridges/pywebview', () => ({
getPywebviewApi: () => ({
enqueue_json: api.enqueue,
get_jd_shop_categories: api.syncCategories,
open_jd_login: api.openJdLogin,
}),
}))
const EMPTY_DASHBOARD = {
pendingTaskCount: 0,
processedTaskCount: 0,
successTaskCount: 0,
failedTaskCount: 0,
}
function historyItem(over: Record<string, unknown> = {}) {
return {
taskId: 88,
taskNo: 'JD-1',
taskStatus: 'RUNNING',
success: false,
errorMessage: null,
shopName: '花屿巷旗舰店',
listTabs: ['ONSALE', 'OFFSALE'],
rowCount: 30,
itemsReceived: 30,
total: 100,
page: 2,
listTab: 'ONSALE',
batches: 1,
createdAt: '2026-11-15T10:00:00',
updatedAt: null,
finishedAt: null,
...over,
}
}
function batchOf(item: Record<string, unknown>) {
return {
items: [
{
task: {
id: item.taskId ?? 88,
taskNo: 'JD-1',
status: item.taskStatus ?? 'RUNNING',
errorMessage: item.errorMessage ?? null,
updatedAt: null,
},
items: [item],
},
],
missingTaskIds: [],
}
}
let wrapper: VueWrapper | null = null
/** el-select/el-option 轻量桩:轮询组用例不带真实 ElementPlus——真件在 fake timers 下
* 的内部计时/Popper 会被 `advanceTimersByTimeAsync(60s)` 一并点燃、打断任务面板轮询链
* (2026-11-17 改版实测 SUCCESS/FAILED 两格因此转红)。下拉形状由分类两格的真实组件
* 用例兜底,这里只保证模板可解析、v-model 透传、选项渲染计数。 */
const ElSelectStub = {
name: 'ElSelect',
props: ['modelValue'],
emits: ['update:modelValue'],
template: '<div class="shop-cat-select"><slot /></div>',
}
const ElOptionStub = {
name: 'ElOption',
props: ['label', 'value'],
template: '<div class="shop-cat-option">{{ label }}</div>',
}
async function mountPage(realSelect = false) {
wrapper = mount(JdCollectTab, {
global: {
// 分类两格用真实 ElementPlus 组件树(经 update:modelValue 模拟点选,
// 弹层 teleport 到 body,不依赖开合动画);其余格用桩。
...(realSelect ? { plugins: [ElementPlus] } : {}),
stubs: {
NotificationBell: true,
// 2026-11-22 JD 页头部挂了密钥设置按钮:面板替身化,别在挂载用例里真发 /user-secrets fetch
ApiSecretSettingsPanel: true,
RouterLink: { template: '<a class="router-link-stub"><slot /></a>' },
'router-link': { template: '<a class="router-link-stub"><slot /></a>' },
...(realSelect ? {} : { 'el-select': ElSelectStub, 'el-option': ElOptionStub }),
},
},
})
await flushPromises()
return wrapper
}
async function startCollect(w: VueWrapper) {
await w.find('.collect-btn').trigger('click')
await flushPromises()
}
/** 「同步分类」拉回的当前店铺分类样本(label/value 与旧快照同形;顺序=同步序/orderNo)。 */
const SYNCED_CATEGORIES = [
{ label: '工作制服', value: '1024347567' },
{ label: '礼服/演出服', value: '1024347568' },
{ label: '拉丁舞服', value: '1024347572' },
]
function syncedResult(over: Record<string, unknown> = {}) {
return { success: true, shopName: '花屿巷旗舰店', shopId: '165515933', categories: SYNCED_CATEGORIES, ...over }
}
async function syncCategories(w: VueWrapper) {
// 2026-11-23 起「登录京麦」按钮退役,.shop-cat-sync 只剩「同步分类」一个;
// 按文案取仍是最稳的定位(将来再加按钮也不会点错)。
const syncBtn = w.findAll('.shop-cat-sync').find((btn) => btn.text().includes('同步分类'))
if (!syncBtn) throw new Error('页面缺「同步分类」按钮')
await syncBtn.trigger('click')
await flushPromises()
}
beforeEach(() => {
vi.useFakeTimers()
localStorage.setItem('username', 'admin')
// 会话旗是模块级单例:jd_login 用例置过旗会泄漏进后续用例的建单预检(误开登录窗)。
resetJdLoginAutoflowForTest()
for (const mock of Object.values(api)) {
// 无桥用例会把 syncCategories 覆写成 undefined,这里按可重置性防御(保持全量 reset 语义)。
if (typeof (mock as { mockReset?: unknown })?.mockReset === 'function') mock.mockReset()
}
api.createJdCollectTask.mockResolvedValue({ taskId: 88, taskNo: 'JD-1', collectChannel: 'LOCAL' })
api.activateJdCollectTask.mockResolvedValue(null)
api.fetchJdCollectCategories.mockResolvedValue([])
api.fetchJdCollectGroups.mockResolvedValue([])
api.enqueue.mockResolvedValue({ success: true })
api.fetchJdCollectDashboard.mockResolvedValue(EMPTY_DASHBOARD)
api.fetchJdCollectHistory.mockResolvedValue({ items: [] })
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(batchOf(historyItem()))
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
vi.useRealTimers()
vi.restoreAllMocks()
localStorage.clear()
})
describe('获取店铺数据:一键采集 + 任务面板', () => {
it('点一次按钮就走完整链路:建单 → 激活 → 推本机队列 → 轮询批量进度', async () => {
const w = await mountPage()
await startCollect(w)
expect(api.createJdCollectTask).toHaveBeenCalledTimes(1)
// 店铺名留空 → 按「京麦后台」占位(客户端从京麦后台现读真实店铺名落库);
// 不选分类=双键空数组(全店采集,后端归一化为 null 进 request_json)
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0, [], [], [])
expect(api.activateJdCollectTask).toHaveBeenCalledWith(88)
expect(api.enqueue).toHaveBeenCalledTimes(1)
const payload = api.enqueue.mock.calls[0][0]
expect(payload.type).toBe('jd-shop-collect-run')
expect(payload.data).toEqual({
taskId: 88,
shopName: '京麦后台',
listTabs: ['ONSALE', 'OFFSALE'],
maxProducts: 0,
shopCategoryNames: [],
shopCategoryIds: [],
})
// 轮询已启动:批量进度端点拿到任务 88
expect(api.fetchJdCollectTaskProgressBatch).toHaveBeenCalled()
const calledIds = api.fetchJdCollectTaskProgressBatch.mock.calls[0][0]
expect(calledIds).toContain(88)
})
it('有 total 时任务卡片显示真实百分比(分母只来自服务端游标)', async () => {
const w = await mountPage()
await startCollect(w)
await flushPromises()
expect(w.find('.task-item').exists()).toBe(true)
expect(w.find('.status').text()).toBe('正在获取店铺数据…')
const bar = w.find('.file-progress-bar')
expect(bar.exists()).toBe(true)
expect(bar.attributes('style')).toContain('width: 30%')
// 百分比文字随 countLabel 一起出(TaskItemCard 有 countLabel 就不显示「总进度 X%」)
expect(w.find('.file-progress-meta').text()).toContain('已采集 30/100 个商品(30%)')
})
it('轮次采集时任务卡片显示「正在采集分类」,页码归 1 不再像重跑(2026-11-21 方案 C)', async () => {
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({ total: 15, itemsReceived: 8, rowCount: 8, page: 1,
shopCatName: '礼服/演出服', batches: 2 })),
)
const w = await mountPage()
await startCollect(w)
await flushPromises()
const text = w.find('.task-item').text()
expect(text).toContain('正在采集分类:礼服/演出服')
// 2026-11-28 精简口径:断点页码/批数等技术游标下屏。
expect(text).not.toContain('断点游标')
expect(text).not.toContain('兜底翻页中')
})
it('合并兜底轮显示「分类名 等」;非轮次任务不出现该行', async () => {
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({ total: 6, itemsReceived: 4, rowCount: 4, page: 1,
shopCatName: '工作制服', shopCatMerged: true, batches: 1 })),
)
const w = await mountPage()
await startCollect(w)
await flushPromises()
expect(w.find('.task-item').text()).toContain('正在采集分类:工作制服 等')
// 非轮次任务(游标无 shopCatName):不出现该行,其余文案不受影响
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({ total: 300, itemsReceived: 30, rowCount: 30, page: 3, batches: 4 })),
)
const w2 = await mountPage()
await startCollect(w2)
await flushPromises()
expect(w2.find('.task-item').text()).not.toContain('正在采集分类')
})
it('没有分母(total 缺失)时只显示已采集行数,不编造百分比', async () => {
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({ total: null, page: null, itemsReceived: 30, rowCount: 30 })),
)
const w = await mountPage()
await startCollect(w)
await flushPromises()
const meta = w.find('.file-progress-meta')
expect(meta.exists()).toBe(true)
expect(meta.text()).toContain('已采集 30 个商品')
expect(meta.text()).toContain('总量未知')
expect(meta.text()).not.toContain('%')
// 分母未知 + 在跑:进度条走不确定态流动条纹(宽度不再按 percent 摆成 0% 空轨道)。
const bar = w.find('.file-progress-bar')
expect(bar.classes()).toContain('indeterminate')
expect(bar.attributes('style') ?? '').not.toContain('width')
})
it('0 行且无分母时报进行时文案,不把「已采集 0 个商品」挂出来像卡死(35089 误删实录)', async () => {
// 首批分片被服务端收下前 itemsReceived 恒 0(页内详情采集 1-3 分钟);「已采集 0 个」
// 让用户以为失败点了删除——35088/35089/35090 三单采集成功但被这样清库(2026-11-21)。
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({ total: null, page: null, itemsReceived: 0, rowCount: 0 })),
)
const w = await mountPage()
await startCollect(w)
await flushPromises()
const meta = w.find('.file-progress-meta')
expect(meta.exists()).toBe(true)
expect(meta.text()).toContain('正在采集,首批数据确认后开始计数…')
expect(meta.text()).not.toContain('已采集 0 个商品')
})
it('0 行但有分母时报「已采 0/N(正在采集中…)」而不是纯 0/N', async () => {
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({ total: 100, page: 1, itemsReceived: 0, rowCount: 0 })),
)
const w = await mountPage()
await startCollect(w)
await flushPromises()
expect(w.find('.file-progress-meta').text()).toContain('已采 0/100 个商品(正在采集中…)')
expect(w.find('.file-progress-meta').text()).not.toContain('已采集 0 个商品')
})
it('分片被拒时进度行以落库 rowCount 为准(itemsReceived 低估不再与行数行自相矛盾)', async () => {
// 34959 实录(2026-11-19):8 行已落京东数据库、分片回传 500 ⇒ 服务端
// itemsReceived=0、rowCount=8,extraLines 显示「已采集 8 个商品」而进度行显示 0。
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({ total: 8, itemsReceived: 0, rowCount: 8 })),
)
const w = await mountPage()
await startCollect(w)
await flushPromises()
const meta = w.find('.file-progress-meta')
expect(meta.text()).toContain('已采集 8/8 个商品(99%)')
expect(meta.text()).not.toContain('已采集 0 个')
// 已落库 8/8:条形按 99% 封顶(SUCCESS 才满格)
expect(w.find('.file-progress-bar').attributes('style')).toContain('width: 99%')
})
it('没有分母且分片被拒时已采行数也取 rowCount 真值', async () => {
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({ total: null, page: null, itemsReceived: 0, rowCount: 8 })),
)
const w = await mountPage()
await startCollect(w)
await flushPromises()
expect(w.find('.file-progress-meta').text()).toContain('已采集 8 个商品')
expect(w.find('.file-progress-meta').text()).not.toContain('已采集 0 个')
})
it('SUCCESS 终态:状态徽章落「获取完成」、进度满格,且从轮询中收手', async () => {
const w = await mountPage()
await startCollect(w)
await flushPromises()
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({ taskStatus: 'SUCCESS', success: true, itemsReceived: 100, rowCount: 100 })),
)
await vi.advanceTimersByTimeAsync(60_000)
await flushPromises()
expect(w.find('.status').text()).toBe('获取完成')
// 终态任务没有进度条(isActiveTask 才有),行数行收口在卡片 extraLines
expect(w.find('.file-progress-bar').exists()).toBe(false)
expect(w.find('.task-item').text()).toContain('已采集 100 个商品')
// 终态即收手:再推进几轮轮询间隔,批量进度不再被调
const callsAfterTerminal = api.fetchJdCollectTaskProgressBatch.mock.calls.length
await vi.advanceTimersByTimeAsync(60_000)
await flushPromises()
expect(api.fetchJdCollectTaskProgressBatch.mock.calls.length).toBe(callsAfterTerminal)
})
it('FAILED 终态:显示服务端原因、出「重试」按钮,重试走原位复位并重新激活推队列', async () => {
const w = await mountPage()
await startCollect(w)
await flushPromises()
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
batchOf(historyItem({
taskStatus: 'FAILED',
success: false,
errorMessage: '京麦后台未登录,请先在客户端登录京麦',
itemsReceived: 30,
})),
)
await vi.advanceTimersByTimeAsync(60_000)
await flushPromises()
expect(w.find('.status').text()).toBe('获取失败')
expect(w.find('.task-item').text()).toContain('京麦后台未登录')
const retryBtn = w.find('.btn-retry')
expect(retryBtn.exists()).toBe(true)
expect(retryBtn.text()).toBe('重试')
await retryBtn.trigger('click')
await flushPromises()
// 铁律 26:原任务复位(不克隆新任务),复位后重新激活并推队列(断点续传)
expect(api.retryClientTask).toHaveBeenCalledWith(88)
expect(api.activateJdCollectTask).toHaveBeenCalledWith(88)
expect(api.enqueue).toHaveBeenCalled()
const pushPayload = api.enqueue.mock.calls.at(-1)?.[0]
expect(pushPayload?.type).toBe('jd-shop-collect-run')
expect(pushPayload?.data?.taskId).toBe(88)
})
it('建单失败:只报错不留假任务,一次批量进度请求也不发', async () => {
api.createJdCollectTask.mockRejectedValue(new Error('缺少登录凭据'))
const w = await mountPage()
await startCollect(w)
expect(w.find('.feedback.error').text()).toContain('缺少登录凭据')
expect(api.fetchJdCollectTaskProgressBatch).not.toHaveBeenCalled()
expect(api.enqueue).not.toHaveBeenCalled()
})
it('激活失败:不推队列(否则首个分片必被「任务不在运行中」拒收),并把原因说给用户', async () => {
api.activateJdCollectTask.mockRejectedValue(new Error('服务暂不可用'))
const w = await mountPage()
await startCollect(w)
expect(api.activateJdCollectTask).toHaveBeenCalledWith(88)
expect(api.enqueue).not.toHaveBeenCalled()
expect(w.find('.feedback.error').text()).toContain('任务激活失败')
})
it('激活时服务端回「已在执行中」:等同激活成功,照常推队列', async () => {
api.activateJdCollectTask.mockRejectedValue(new Error('任务已在执行中(客户端已认领)'))
const w = await mountPage()
await startCollect(w)
expect(api.enqueue).toHaveBeenCalledTimes(1)
expect(w.find('.feedback.error').exists()).toBe(false)
})
it('推送本机队列失败:走 amber notice 提示(不占红色 error),建单与轮询照常', async () => {
// 2026-11-19 用户实录:建单撞上客户端升级重启窗口,推送失败被渲染成红色「推送失败」
// 横幅;实为设计内兜底慢路径(客户端 60 秒一轮 pull-pending 自动认领,最多晚约 1
// 分钟)。桥返回失败必须按提示展示,红色 error 只留给真失败(建单/激活失败)。
api.enqueue.mockResolvedValue({ success: false, error: 'queue is closing' })
const w = await mountPage()
await startCollect(w)
expect(api.createJdCollectTask).toHaveBeenCalledTimes(1)
const notice = w.find('.feedback.notice')
expect(notice.exists()).toBe(true)
expect(notice.text()).toContain('任务已创建')
expect(notice.text()).toContain('自动领取')
expect(notice.text()).not.toContain('失败')
expect(w.find('.feedback.error').exists()).toBe(false)
// 建单成功即进轮询:兜底拉取认领后进度照常上屏
expect(api.fetchJdCollectTaskProgressBatch).toHaveBeenCalled()
})
it('推送抛异常:同样走 notice 提示、不回滚建单', async () => {
api.enqueue.mockRejectedValue(new Error('bridge gone'))
const w = await mountPage()
await startCollect(w)
const notice = w.find('.feedback.notice')
expect(notice.exists()).toBe(true)
expect(notice.text()).toContain('自动领取')
expect(notice.text()).not.toContain('失败')
expect(w.find('.feedback.error').exists()).toBe(false)
expect(api.fetchJdCollectTaskProgressBatch).toHaveBeenCalled()
})
it('下拉选分类后建单:店内分类双键随建单请求体与推送载荷同链下发', async () => {
// 2026-11-16 客户口径「类目不需要只要分类」「选京麦的内部分类去采集」;
// 2026-11-17 客户口径「不要全展示出来,弄个下拉式多选」;2026-11-19 选项集改
// 「同步分类」桥实时拉取(每家店的店内分类名字与 id 都不同,冻结快照已退役)。
// 建单请求体与推送载荷带 label+id 双键、按选项集原序反查(行级填充形状未取证,
// 客户端任一键命中即命中)——选中项用同步样本真实行,贴合下发形状。
api.syncCategories.mockResolvedValue(syncedResult())
const w = await mountPage(true)
await syncCategories(w)
const select = w.findComponent(ElSelect)
expect(select.exists(), '采集分类必须是下拉多选(el-select),不再是逐条复选框').toBe(true)
await select.vm.$emit('update:modelValue', ['1024347572', '1024347567'])
await flushPromises()
await startCollect(w)
// 双键顺序恒等于选项集序(工作制服在前),与点选先后无关——同源反查,不随 UI 顺序漂。
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0, [],
['工作制服', '拉丁舞服'], ['1024347567', '1024347572'])
const payload = api.enqueue.mock.calls[0][0]
expect(payload.data).toEqual({
taskId: 88,
shopName: '京麦后台',
listTabs: ['ONSALE', 'OFFSALE'],
maxProducts: 0,
shopCategoryNames: ['工作制服', '拉丁舞服'],
shopCategoryIds: ['1024347567', '1024347572'],
})
})
it('同步分类成功:选项集换成当前店铺实时分类并显示店铺名(不再是 9 个冻结快照)', async () => {
const w = await mountPage(true)
const block = w.findAll('.category-block').find((el) => el.text().includes('采集分类'))
expect(block, '必须有「采集分类(可选,多选)」块').toBeTruthy()
// 未同步:选项集为空(不预置任何快照),提示指向「同步分类」;空选=全店采集。
expect(w.findAllComponents(ElOption).length).toBe(0)
expect(block!.text()).toContain('未同步或空选=全店采集')
expect(block!.text()).not.toContain('2026-11-16 快照')
expect(block!.findComponent(ElSelect).props('placeholder')).toBe('全店采集(点击选择分类)')
api.syncCategories.mockResolvedValue(syncedResult())
await syncCategories(w)
expect(w.findAllComponents(ElOption).length).toBe(SYNCED_CATEGORIES.length,
'选项集必须等于桥拉回的当前店铺分类,不是冻结快照的 9 个')
expect(block!.text()).toContain('已同步店铺「花屿巷旗舰店」:3 个分类')
expect(block!.text()).not.toContain('未同步')
// 按钮回到可再同步态(店铺侧改了分类可随时重拉)
const syncBtn = w.findAll('.shop-cat-sync').find((btn) => btn.text().includes('同步分类'))
expect(syncBtn, '页面缺「同步分类」按钮').toBeTruthy()
expect(syncBtn!.text()).toBe('同步分类')
expect(syncBtn!.attributes('disabled')).toBeUndefined()
})
it('同步失败 jd_busy:京东任务在跑是设计内等待,走 amber notice 不占红色 error', async () => {
api.syncCategories.mockResolvedValue(
syncedResult({ success: false, code: 'jd_busy', error: '京东采集/发布任务正在运行,请等任务结束后再同步分类' }))
const w = await mountPage(true)
await syncCategories(w)
const notice = w.find('.feedback.notice')
expect(notice.exists()).toBe(true)
expect(notice.text()).toContain('任务正在运行')
expect(w.find('.feedback.error').exists()).toBe(false)
// 分类照常未同步:选项集仍空(busy 后不得回落假数据)
expect(w.findAllComponents(ElOption).length).toBe(0)
})
it('同步失败 jd_login:自动开京麦登录窗,登录成功后自动重拉分类(登录按钮已退役)', async () => {
// 第一次同步回 jd_login ⇒ 自动开登录窗(already_logged_in 秒回)⇒ 自动重拉第二次成功。
api.syncCategories
.mockResolvedValueOnce(syncedResult({ success: false, code: 'jd_login',
error: '京麦未登录(登录态失效),请先在客户端登录京麦' }))
.mockResolvedValueOnce(syncedResult())
api.openJdLogin.mockResolvedValue({ success: true, code: 'already_logged_in', message: '京麦已是登录状态' })
const w = await mountPage(true)
await syncCategories(w)
expect(api.openJdLogin).toHaveBeenCalledTimes(1)
expect(api.syncCategories).toHaveBeenCalledTimes(2, '登录成功后必须自动重拉一次分类(闭环,不劳用户再点)')
expect(w.findAllComponents(ElOption).length).toBe(SYNCED_CATEGORIES.length)
expect(w.find('.feedback.error').exists()).toBe(false)
})
it('同步失败 jd_login 且登录未完成:amber 提示等登录,不递归开窗不假同步', async () => {
// 超时档(窗口仍开着等人工登录):只提示、不重拉——用户登完再点同步/获取。
api.syncCategories.mockResolvedValue(
syncedResult({ success: false, code: 'jd_login', error: '京麦未登录(登录态失效),请先在客户端登录京麦' }))
api.openJdLogin.mockResolvedValue({ success: false, code: 'timeout', error: '等待登录超时' })
const w = await mountPage(true)
await syncCategories(w)
const notice = w.find('.feedback.notice')
expect(notice.exists()).toBe(true)
expect(notice.text()).toContain('登录')
expect(w.find('.feedback.error').exists()).toBe(false)
expect(api.openJdLogin).toHaveBeenCalledTimes(1)
expect(api.syncCategories).toHaveBeenCalledTimes(1, '登录未完成不得自动重拉(再拉还是 jd_login)')
expect(w.findAllComponents(ElOption).length).toBe(0)
})
it('老客户端无同步桥:按钮置灰,全店采集不受影响', async () => {
const originalSync = api.syncCategories
api.syncCategories = undefined as unknown as typeof api.syncCategories
try {
const w = await mountPage(true)
await flushPromises()
const syncBtn = w.findAll('.shop-cat-sync').find((btn) => btn.text().includes('同步分类'))
expect(syncBtn, '页面缺「同步分类」按钮').toBeTruthy()
// 桥上没有 get_jd_shop_categories(老客户端/浏览器打开)⇒ 按钮置灰,
// 用户根本点不到(无桥提示 SYNC_UNAVAILABLE_NOTE 的形状由 jd-collect-tab 纯测试钉住)
expect(syncBtn!.attributes('disabled')).toBeDefined()
expect(w.findAllComponents(ElOption).length).toBe(0)
// 全店采集主链路不依赖分类:建单双键空数组照常
await startCollect(w)
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0, [], [], [])
} finally {
// 覆写必须还原:hoisted 对象的 undefined 会穿过 beforeEach 的 mockReset 泄漏到后续用例
api.syncCategories = originalSync
}
})
it('重同步换店:清掉不属于当前店铺的已选分类,防止跨店 id 误过滤', async () => {
api.syncCategories.mockResolvedValue(syncedResult())
const w = await mountPage(true)
await syncCategories(w)
const select = w.findComponent(ElSelect)
await select.vm.$emit('update:modelValue', ['1024347567', '1024347572'])
await flushPromises()
// 换了一家店:新分类集与旧店 id 无交集 ⇒ 旧已选项必须被清掉并告知
api.syncCategories.mockResolvedValue(syncedResult({
shopName: '另一家旗舰店',
categories: [
{ label: '男士上衣', value: '9900000001' },
{ label: '其他', value: '9900000002' },
],
}))
await syncCategories(w)
expect(w.text()).toContain('清除了 2 个不属于当前店铺的已选项')
expect(w.findAllComponents(ElOption).length).toBe(2)
await startCollect(w)
const payload = api.enqueue.mock.calls[0][0]
// 跨店残留 id 不得进建单请求体(否则按另一家店的分类过滤,0 行命中)
expect(payload.data.shopCategoryIds).toEqual([])
expect(payload.data.shopCategoryNames).toEqual([])
})
/** 2026-11-20 客户口径「加个状态勾选,采集售卖中或已下架的,多选」:状态从写死两项
* 改为页面勾选;勾选结果必须同时进建单 listTabs 与推送载荷(两处不同源=界面勾了、
* 客户端照旧跑两档)。 */
it('采集状态多选:只勾「已下架」时建单与推送载荷都只带 OFFSALE', async () => {
const w = await mountPage()
const checks = w.findAll('.tab-check input')
expect(checks.length, '必须有售卖中/已下架两个勾选框').toBe(2)
// 默认两项都勾=旧行为(不悄悄变成只采一档)
expect((checks[0].element as HTMLInputElement).checked).toBe(true)
expect((checks[1].element as HTMLInputElement).checked).toBe(true)
await checks[0].trigger('change') // 取消「售卖中」
await flushPromises()
expect((checks[0].element as HTMLInputElement).checked).toBe(false)
await startCollect(w)
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['OFFSALE'], 0, [], [], [])
expect(api.enqueue.mock.calls[0][0].data.listTabs).toEqual(['OFFSALE'])
})
it('采集状态多选:两项都不勾时按钮禁用并说明原因,点了也不建单', async () => {
const w = await mountPage()
const checks = w.findAll('.tab-check input')
await checks[0].trigger('change')
await checks[1].trigger('change')
await flushPromises()
const btn = w.find('.collect-btn')
expect(btn.attributes('disabled')).toBeDefined()
expect(btn.text()).toBe('请先勾选采集状态')
await btn.trigger('click')
await flushPromises()
// 第二道:即便事件穿透到处理函数,空选也拦在建单之前
expect(api.createJdCollectTask).not.toHaveBeenCalled()
// 提示文案随勾选状态实时说明原因(按钮禁用是第一道)
expect(w.findAll('.category-block')[0].text()).toContain('至少勾选一个采集状态')
})
})