Files
crawler-plugin/admin-frontend-vue/tests/mount/jd-database-page.mount.test.ts
T

603 lines
32 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.4 Phase 5)的挂载契约。
*
* 形态:panel-box + 筛选行(店铺/商品编码/标题关键字/分类/同步起止 date 对)+
* 查询/重置/店铺分类 + 自绘明细表(点行开详情抽屉)+ OldPagination;
* 公司 tab 切换=清筛选重取(company-tab-wiring 同口径)。
* 商品状态筛选/列与导出按钮已随 2026-11-15 客户口径从前端下线(后端端点保留)。
* 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。
*
* 跑法:`npx vitest run tests/mount/jd-database-page.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import JdDatabasePage from '@/pages/jd/JdDatabasePage.vue'
import JdProductGroupDialog from '@/pages/jd/JdProductGroupDialog.vue'
import { useAdminSessionStore } from '@/stores/admin-session'
import { useCompanyTabStore } from '@/stores/company-tab'
const jdApi = vi.hoisted(() => ({
JD_PRODUCT_ENDPOINT: '/api/admin/jd-products',
JD_PRODUCT_GROUP_ENDPOINT: '/api/admin/jd-product-groups',
fetchJdProductList: vi.fn(),
fetchJdProductDetail: vi.fn(),
deleteJdProducts: vi.fn(),
fetchJdProductGroups: vi.fn(),
fetchJdProductCategories: vi.fn(),
createJdProductGroup: vi.fn(),
updateJdProductGroup: vi.fn(),
deleteJdProductGroup: vi.fn(),
updateJdProduct: vi.fn(),
batchAssignJdProductGroup: vi.fn(),
}))
const confirmMock = vi.hoisted(() => vi.fn())
vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi)
vi.mock('@/components/admin-confirm', () => ({ openAdminConfirm: confirmMock }))
function item(id: number, over: Record<string, unknown> = {}) {
return {
id,
shopId: 3,
shopName: '旗舰自营店',
productCode: `JD-100${id}`,
skuId: `SKU-${id}`,
itemNum: `ITEM-${id}`,
skuCount: 12,
healthScore: 81,
title: '304不锈钢保温杯大容量便携',
brand: '锅宝',
categoryPath: '家居 > 厨具 > 保温杯',
priceMin: '12.90',
priceMax: '15.90',
stockTotal: 500,
saleStatus: '上架中',
listTab: 'search',
jdCreatedAt: '2026-11-07 18:49:47',
jdOnlineAt: '2026-11-12 15:03:37',
jdUpdatedAt: '2026-11-13 14:06:07',
mainImageUrl: `https://img.example/main-${id}.jpg`,
attrCount: 6,
imageCount: 9,
groupId: 7,
groupName: '甲组',
syncedAt: '2026-11-12 09:00:00',
...over,
}
}
let pinia: Pinia
beforeEach(() => {
vi.clearAllMocks()
pinia = createPinia()
setActivePinia(pinia)
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
useCompanyTabStore().setActiveId(1)
jdApi.fetchJdProductGroups.mockResolvedValue([])
jdApi.fetchJdProductCategories.mockResolvedValue([])
confirmMock.mockResolvedValue(true)
})
async function mountWith(payload: unknown): Promise<VueWrapper<Element>> {
jdApi.fetchJdProductList.mockImplementation(() => Promise.resolve(payload))
const wrapper = mount(JdDatabasePage, { global: { plugins: [pinia] } })
await flushPromises()
await flushPromises()
return wrapper
}
describe('京东数据库页(v1.4 Phase 5)', () => {
it('挂载后按首屏分页参数取列表(pageSize 默认 20、带公司 tab),行数=本页条数', async () => {
const wrapper = await mountWith({ items: [item(1), item(2), item(3)], total: 42, page: 1, pageSize: 20 })
expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(1)
const firstCall = jdApi.fetchJdProductList.mock.calls[0][0]
expect(firstCall.page).toBe(1)
expect(firstCall.pageSize).toBe(20)
expect(firstCall.companyId).toBe(1)
expect(wrapper.findAll('tbody tr')).toHaveLength(3)
expect(wrapper.find('.jd-summary').text()).toContain('共 42 条京东商品')
})
it('行列字段与顺序对齐京麦(2026-11-15 用户口径):勾选/店铺/分组/商品信息(图+标题+编码+货号+品牌·类目+SKU/信息分)/总库存/价格/上架时间·商品状态/创建/修改/同步/操作(11 列)', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
const cells = wrapper.findAll('tbody tr')[0].findAll('td')
expect(cells).toHaveLength(11)
expect(cells[0].find('input[type="checkbox"]').exists()).toBe(true, '第 1 列是勾选框')
expect(cells[1].text()).toBe('旗舰自营店', '第 2 列=店铺(admin 专属,置前)')
expect(cells[2].text()).toBe('甲组', '第 3 列=分组(admin 专属)')
// 商品信息列=京麦同款合并布局:主图+信息分+标题+商品编码+货号+品牌·类目行+SKU 标签。
const info = cells[3]
expect(info.find('.jd-thumb').exists()).toBe(true, '商品信息列含主图')
expect(info.text()).toContain('304不锈钢保温杯')
expect(info.text()).toContain('JD-1001', '商品编码并入商品信息列')
expect(info.text()).toContain('ITEM-1', '货号并入商品信息列')
expect(info.text()).toContain('锅宝', '品牌并入商品信息列(京麦品牌·类目行)')
expect(info.text()).toContain('家居 > 厨具 > 保温杯', '类目随品牌·类目行上列表(京麦同款)')
expect(info.text()).toContain('12个SKU')
expect(info.text()).toContain('信息分 81')
expect(cells[4].text()).toBe('500', '第 4 数据列=总库存(京麦第 2 列)')
expect(cells[5].text()).toBe('12.90 ~ 15.90', '第 5 数据列=价格(京麦第 3 列)')
expect(cells[6].text()).toContain('上架中', '第 6 数据列=上架时间/商品状态(京麦合并列)')
expect(cells[6].find('.jd-sale-dot').exists()).toBe(true, '状态带京麦同款圆点')
expect(cells[7].text()).not.toBe('-', '第 7 数据列=创建时间')
expect(cells[8].text()).not.toBe('-', '第 8 数据列=修改时间')
expect(cells[9].text()).not.toBe('-', '第 9 数据列=同步时间(admin 专属,置末)')
expect(cells[10].text()).toContain('编辑', '第 10 数据列=操作(编辑/删除)')
// 表头字段名与顺序与京麦一致;品牌/类目不再是独立列(收进商品信息)。
const headerText = wrapper.find('thead').text()
for (const gone of ['品牌', '类目']) {
expect(headerText).not.toContain(gone, `${gone}不再是独立列(京麦把它们收进商品信息)`)
}
for (const head of ['商品信息', '总库存', '价格', '上架时间 / 商品状态', '创建时间', '修改时间', '同步时间']) {
expect(headerText).toContain(head, `表头必须有「${head}」(京麦字段名)`)
}
expect(wrapper.find('.jd-thumb').exists()).toBe(true, '商品信息列渲染缩略图')
})
it('操作列删除按钮防冒泡且走确认弹窗:确认后调 deleteJdProducts,取消不动(2026-11-15 行级删除)', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
// beforeEach 默认 confirm=true;本例先翻回 false 验「取消不动」。
confirmMock.mockResolvedValue(false)
const opsCell = wrapper.findAll('tbody tr')[0].findAll('td')[10]
await opsCell.findAll('button').find((b) => b.text() === '删除')!.trigger('click')
await flushPromises()
// 防冒泡:点删除不得顺手打开详情抽屉(抽屉的可视判据=.drawer 出现)。
expect(wrapper.find('.drawer').exists()).toBe(false, '删除按钮 @click.stop,点它不开详情抽屉')
expect(confirmMock).toHaveBeenCalledTimes(1, '删除必须过二次确认')
expect(jdApi.deleteJdProducts).toHaveBeenCalledTimes(0, '确认弹窗取消时不发删除请求')
// 确认后:deleteJdProducts 按 id 直删(公共库写侧无公司维度,2026-11-15 公共化)。
confirmMock.mockResolvedValue(true)
jdApi.deleteJdProducts.mockResolvedValueOnce({ deleted: 1, imagesDeleted: 0, objectsDeleted: 0, objectsKept: 0, objectsSkipped: 0 })
await wrapper.findAll('tbody tr')[0].findAll('td')[10].findAll('button').find((b) => b.text() === '删除')!.trigger('click')
await flushPromises()
expect(jdApi.deleteJdProducts).toHaveBeenCalledWith([1])
})
it('操作列编辑按钮防冒泡且打开编辑抽屉(抽屉自取详情回填,2026-11-15 行级编辑)', async () => {
// fetchJdProductDetail 的返回已由 parseJdProductDetail 归一成 {item, attrGroups, images, skus, attrJsonRaw}。
jdApi.fetchJdProductDetail.mockResolvedValue({
item: {
id: 1,
title: '304不锈钢保温杯大容量便携',
brand: '锅宝',
categoryPath: '家居 > 厨具 > 保温杯',
itemNum: 'ITEM-1',
priceMin: '12.90',
priceMax: '15.90',
stockTotal: 500,
saleStatus: '上架中',
groupId: 7,
groupName: '甲组',
productCode: 'JD-1001',
shopName: '旗舰自营店',
},
attrGroups: [],
images: [],
skus: [],
attrJsonRaw: '',
})
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
const opsCell = wrapper.findAll('tbody tr')[0].findAll('td')[10]
await opsCell.findAll('button').find((b) => b.text() === '编辑')!.trigger('click')
await flushPromises()
await flushPromises()
expect(wrapper.find('.drawer').exists()).toBe(true, '编辑抽屉打开')
expect(wrapper.text()).toContain('编辑商品', '抽屉标题点商品')
// 抽屉按 id 自取详情回填(公共库详情无公司维度)。
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1)
// 编辑抽屉的保存提示文案点名人工编辑锁后果(用户保存前看得见「采集不再覆盖」)。
expect(wrapper.text()).toContain('人工维护', '保存后果提示常驻(V199 人工编辑锁)')
})
it('商品信息列:主图无 URL 显示「无图」占位、healthScore 为空不出信息分行、skuCount 为空不出 SKU 标签', async () => {
const wrapper = await mountWith({
items: [item(1), item(2, { mainImageUrl: '', healthScore: null, skuCount: null })],
total: 2, page: 1, pageSize: 20,
})
const rowTexts = wrapper.findAll('tbody tr').map((tr) => tr.text())
expect(wrapper.findAll('img.jd-thumb')).toHaveLength(1, '只有有自有桶 URL 的行出真图(无图占位是 span,不冒充 img)')
expect(rowTexts[1]).toContain('无图')
expect(rowTexts[1]).not.toContain('信息分')
expect(rowTexts[1]).not.toContain('个SKU')
})
it('商品编码旁复制按钮:写入剪贴板且不冒泡开抽屉', async () => {
const writeText = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '复制前抽屉未开')
await wrapper.findAll('.jd-copy-btn')[0].trigger('click')
expect(writeText).toHaveBeenCalledWith('JD-1001')
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '点复制按钮不冒泡开抽屉')
})
it('分类读不到的那行展示「未分类」(不猜名字;2026-11-15「分组管理」改「店铺分类」只换措辞)', async () => {
const wrapper = await mountWith({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 })
expect(wrapper.findAll('tbody tr')[0].findAll('td')[2].text()).toBe('未分类')
})
it('筛选生效:店铺/编码/关键字/分组/起止日期,查询回第一页重发', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
const textInputs = wrapper.findAll('.form-group input[type="text"]')
expect(textInputs).toHaveLength(3, '店铺+商品编码+标题关键字三个文本筛选框(商品状态已下线)')
await textInputs[0].setValue('旗舰自营店')
await textInputs[1].setValue('JD-1001')
await textInputs[2].setValue('保温杯')
await wrapper.find('select').setValue('7')
const dateInputs = wrapper.findAll('input[type="date"]')
await dateInputs[0].setValue('2026-11-01')
await dateInputs[1].setValue('2026-11-09')
await wrapper.findAll('button').find((b) => b.text() === '查询')!.trigger('click')
await flushPromises()
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect(last).toMatchObject({
shopName: '旗舰自营店',
productCode: 'JD-1001',
titleKeyword: '保温杯',
groupId: '7',
syncedFrom: '2026-11-01',
syncedTo: '2026-11-09',
page: 1,
companyId: 1,
})
expect(last).not.toHaveProperty('saleStatus', '商品状态筛选已下线,入参不再带 saleStatus')
})
it('分组下拉选中即查', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([
{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 },
{ id: 8, name: '乙组', sortOrder: 1, productCount: 1 },
])
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledWith()
const groupSelect = wrapper.find('select')
const optionTexts = groupSelect.findAll('option').map((o) => o.text())
expect(optionTexts).toContain('全部分类')
expect(optionTexts).toContain('甲组')
const callsBeforeSelect = jdApi.fetchJdProductList.mock.calls.length
await groupSelect.setValue('7')
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBeforeSelect + 1, '选中分组必须立刻重查')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ groupId: '7', page: 1 })
})
it('类目下拉:选项来自 GET /categories(带商品数),选中即查回第一页', async () => {
jdApi.fetchJdProductCategories.mockResolvedValue([
{ name: '服饰内衣', productCount: 120 },
{ name: '运动户外', productCount: 8 },
])
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
expect(jdApi.fetchJdProductCategories).toHaveBeenCalledWith(1)
// 第 1 个 select = 分组(既有契约不动),类目下拉紧随其后
const selects = wrapper.findAll('.jd-filter-row select')
expect(selects).toHaveLength(2)
const categorySelect = selects[1]
const optionTexts = categorySelect.findAll('option').map((o) => o.text())
expect(optionTexts[0]).toBe('全部类目')
expect(optionTexts).toContain('服饰内衣(120)')
const callsBeforeSelect = jdApi.fetchJdProductList.mock.calls.length
await categorySelect.setValue('运动户外')
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(callsBeforeSelect + 1, '选中类目必须立刻重查')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ category: '运动户外', page: 1 })
})
it('重置把筛选面回空并回第一页重取', async () => {
const wrapper = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
const textInputs = wrapper.findAll('.form-group input[type="text"]')
await textInputs[0].setValue('旗舰自营店')
await textInputs[2].setValue('保温杯')
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
await wrapper.findAll('button').find((b) => b.text() === '重置')!.trigger('click')
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore)
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect(last).toMatchObject({ shopName: '', titleKeyword: '', page: 1 }, '重置后筛选全空、回第一页')
})
it('翻页与改每页条数都重发请求,改条数回第一页', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 42, page: 2, pageSize: 20 })
await wrapper.findAll('button').find((b) => b.text() === '下一页')!.trigger('click')
await flushPromises()
expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(2)
expect(jdApi.fetchJdProductList.mock.calls[1][0].page).toBe(3)
const sizeSelect = wrapper.find('.page-size-select')
await sizeSelect.setValue('50')
await flushPromises()
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect(last.pageSize).toBe(50)
expect(last.page).toBe(1, '改每页条数后回第一页')
})
it('导出按钮已下线:筛选行不再出现「导出」(2026-11-15 客户口径「导出也不用」)', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
const btn = wrapper.findAll('button').find((b) => b.text() === '导出')
expect(btn, '导出按钮必须已从前端移除').toBeUndefined()
expect(jdApi.fetchJdProductList).toHaveBeenCalledTimes(1, '下线导出不影响列表首屏')
})
it('点行打开详情抽屉:按 id 取详情(公共库无公司维度),attrGroups 分块渲染', async () => {
jdApi.fetchJdProductDetail.mockImplementation(() =>
Promise.resolve({
item: item(1),
attrGroups: [{ groupName: '规格', attrs: [{ key: 'capacity', label: '容量', value: '500ml' }] }],
images: [{ imageType: 'MAIN', attrName: '', sortNo: 1, url: 'https://img.example/main-1.jpg', byteSize: null, width: 800, height: 800 }],
skus: [],
attrJsonRaw: '',
}),
)
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
expect(wrapper.find('.drawer-mask').exists()).toBe(false, '初始不显示抽屉')
await wrapper.findAll('tbody tr')[0].trigger('click')
await flushPromises()
await flushPromises()
expect(wrapper.find('.drawer-mask').exists()).toBe(true)
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledTimes(1)
expect(jdApi.fetchJdProductDetail).toHaveBeenCalledWith(1)
expect(wrapper.find('.drawer-mask').text()).toContain('基本信息')
expect(wrapper.find('.drawer-mask').text()).toContain('规格')
expect(wrapper.find('.drawer-mask').text()).toContain('容量')
expect(wrapper.find('.drawer-mask').text()).toContain('500ml')
expect(wrapper.find('.drawer-mask').text()).toContain('主图')
const drawerText = wrapper.find('.drawer-mask').text()
expect(drawerText).toContain('货号')
expect(drawerText).toContain('ITEM-1')
expect(drawerText).toContain('信息分')
expect(drawerText).toContain('上架时间')
// B104:详情里全量可见(店铺/分组 2026-11-15 起也上了列表,抽屉仍保留)。
expect(drawerText).toContain('家居 > 厨具 > 保温杯')
expect(drawerText).toContain('SKU 数')
expect(drawerText).toContain('京东创建时间')
expect(drawerText).toContain('京东修改时间')
expect(drawerText).toContain('旗舰自营店')
expect(drawerText).toContain('甲组')
})
it('详情抽屉的销售属性=京麦那 12 行 SKU 矩阵:颜色/尺码两列维度 + 京东价 + 库存 + skuId', async () => {
const skuRows = [
{ skuId: '10238877506570', skuName: '花屿巷… 上衣 S', skuSeq: '1', price: 162, stock: 200, sortNo: 0,
saleAttrs: [{ name: '颜色', value: '上衣' }, { name: '尺码', value: 'S' }] },
{ skuId: '10238877506574', skuName: '花屿巷… 上衣 M', skuSeq: '2', price: 168, stock: 150, sortNo: 1,
saleAttrs: [{ name: '颜色', value: '上衣' }, { name: '尺码', value: 'M' }] },
{ skuId: '10238877506580', skuName: '花屿巷… 半裙 S', skuSeq: '3', price: 162, stock: 80, sortNo: 2,
saleAttrs: [{ name: '颜色', value: '半裙' }, { name: '尺码', value: 'S' }] },
]
jdApi.fetchJdProductDetail.mockImplementation(() =>
Promise.resolve({
item: item(1),
attrGroups: [],
images: [],
skus: skuRows,
attrJsonRaw: '',
}),
)
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
await wrapper.findAll('tbody tr')[0].trigger('click')
await flushPromises()
await flushPromises()
expect(wrapper.find('.drawer-mask').text()).toContain('销售属性 / SKU 矩阵')
const headers = wrapper.findAll('.sku-table thead th').map((th) => th.text())
expect(headers).toEqual(['序号', '颜色', '尺码', '京东价', '库存', 'SKU ID', 'SKU 名称'],
'维度列从各 SKU 的 saleAttrs 派生(京麦「颜色/尺码」两列)')
const rows = wrapper.findAll('.sku-table tbody tr')
expect(rows).toHaveLength(3, '12 行矩阵按入库行数渲染')
const first = rows[0].findAll('td').map((td) => td.text())
expect(first).toEqual(['1', '上衣', 'S', '¥162', '200', '10238877506570', '花屿巷… 上衣 S'])
expect(rows[1].findAll('td').map((td) => td.text())[3]).toBe('¥168', '每行自己的京东价')
expect(wrapper.find('.drawer-mask').text()).toContain('3 个 SKU')
expect(wrapper.find('.drawer-mask').text()).toContain('库存 430', '汇总=各行库存之和')
})
it('旧行没有 SKU 矩阵时给可解释的空态(不渲染空表、不静默吞)', async () => {
jdApi.fetchJdProductDetail.mockImplementation(() =>
Promise.resolve({ item: item(1), attrGroups: [], images: [], skus: [], attrJsonRaw: '' }),
)
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
await wrapper.findAll('tbody tr')[0].trigger('click')
await flushPromises()
await flushPromises()
expect(wrapper.find('.sku-table').exists()).toBe(false)
expect(wrapper.find('.drawer-mask').text()).toContain('暂无 SKU 矩阵')
})
it('删除:勾选两行点删除 → 二次确认点名数量与桶清理 → 批量端点按 id 直删(公共库无公司维度),成功后刷新并清勾选', async () => {
jdApi.deleteJdProducts.mockResolvedValue({ deleted: 2, imagesDeleted: 18, objectsDeleted: 16, objectsKept: 2, objectsSkipped: 0 })
const wrapper = await mountWith({ items: [item(1), item(2)], total: 2, page: 1, pageSize: 20 })
const boxes = wrapper.findAll('tbody input[type="checkbox"]')
await boxes[0].setValue(true)
await boxes[1].setValue(true)
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true, '勾选后工具栏出「删除勾选」')
await wrapper.find('.jd-delete-btn').trigger('click')
await flushPromises()
await flushPromises()
expect(confirmMock).toHaveBeenCalledTimes(1)
const options = confirmMock.mock.calls[0][0]
expect(options.title).toBe('删除京东商品')
expect(options.message).toContain('确定删除勾选的 2 个商品吗')
expect(options.message).toContain('jd-products 桶内图片文件一并删除', '确认弹窗必须点名「桶文件也会删」')
expect(options.danger).toBe(true)
expect(jdApi.deleteJdProducts).toHaveBeenCalledTimes(1)
expect(jdApi.deleteJdProducts).toHaveBeenCalledWith([1, 2])
expect(document.body.textContent).toContain('已删除 2 个商品')
expect(document.body.textContent).toContain('2 个共用图片保留', '共用对象计数要透出到反馈')
// 成功后重取列表并清勾选:工具栏按钮消失。
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(1)
expect(wrapper.find('.jd-delete-btn').exists()).toBe(false)
})
it('删除:确认弹窗点取消就不发请求(防误删的第一道闸)', async () => {
confirmMock.mockResolvedValue(false)
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
await wrapper.find('.jd-delete-btn').trigger('click')
await flushPromises()
expect(confirmMock).toHaveBeenCalledTimes(1)
expect(jdApi.deleteJdProducts).not.toHaveBeenCalled()
})
it('删除失败把后端「本次未删除任何数据」文案弹出来(整批拒绝的语义必须到界面)', async () => {
jdApi.deleteJdProducts.mockRejectedValue(new Error('桶内对象删除失败,本次未删除任何数据(jd-products/5/a.jpg):oss 5xx'))
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
await wrapper.find('.jd-delete-btn').trigger('click')
await flushPromises()
await flushPromises()
expect(document.body.textContent).toContain('本次未删除任何数据')
// 失败后勾选保留,用户可重试。
expect(wrapper.find('.jd-delete-btn').exists()).toBe(true)
})
it('店铺分类弹窗(原「管理分组」):打开即拉分类列表与右栏商品行集,变更后刷新分类下拉与列表', async () => {
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
await wrapper.findAll('button').find((b) => b.text() === '店铺分类')!.trigger('click')
await flushPromises()
await flushPromises()
expect(wrapper.find('.group-modal').exists()).toBe(true)
expect(wrapper.find('.group-modal').text()).toContain('店铺分类', '弹窗标题改「店铺分类」')
// 打开弹窗 = 拉一次分类列表(第 2 次:首屏已拉过一次;分类全平台一份、不带公司维度)
expect(jdApi.fetchJdProductGroups).toHaveBeenCalledTimes(2)
expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith()
// 右栏取数复用 fetchJdProductList:不带公司维度(公共库),默认「全部」范围不带 ungrouped=true。
const dialogCall = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect(dialogCall.companyId).toBeNull()
expect(dialogCall.ungrouped).toBe(false)
// 模拟分类管理里删了一个分类:emit changed → 页面刷新分类下拉与列表(回第一页)
wrapper.findComponent(JdProductGroupDialog).vm.$emit('changed')
await flushPromises()
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore)
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ page: 1, companyId: 1 })
})
it('店铺分类弹窗:左侧点亮分类→勾选商品→「归入所选分类」按(ids, 目标分类 id)调批量归类', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([
{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 },
{ id: 8, name: '乙组', sortOrder: 1, productCount: 0 },
])
jdApi.fetchJdProductList.mockImplementation(() =>
Promise.resolve({ items: [item(1), item(2)], total: 2, page: 1, pageSize: 20 }))
const wrapper = mount(JdProductGroupDialog, { props: { visible: false }, global: { plugins: [pinia] } })
await wrapper.setProps({ visible: true })
await flushPromises()
await flushPromises()
// 左侧点亮「甲组」=归类目标;只点亮还没勾选时按钮仍置灰(归入=目标+勾选两者齐备)。
const assignBtn = () => wrapper.findAll('button').find((b) => b.text().includes('归入'))
expect(assignBtn()!.attributes('disabled')).toBeDefined()
await wrapper.findAll('.group-row')[0].trigger('click')
await flushPromises()
expect(assignBtn()!.attributes('disabled')).toBeDefined()
expect(assignBtn()!.text()).toContain('甲组', '按钮点名归类目标')
// 勾选两行 → 按钮点亮 → 归入「甲组」。
const boxes = wrapper.findAll('tbody input[type="checkbox"]')
await boxes[0].setValue(true)
await boxes[1].setValue(true)
expect(assignBtn()!.attributes('disabled')).toBeUndefined()
jdApi.batchAssignJdProductGroup.mockResolvedValue(2)
await assignBtn()!.trigger('click')
await flushPromises()
await flushPromises()
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledTimes(1)
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1, 2], 7)
// 成功后刷新左栏分类数(商品数)与右栏行集,勾选清空。
expect(jdApi.fetchJdProductGroups).toHaveBeenCalled()
expect(wrapper.findAll('tbody input[type="checkbox"]').every((b) => !(b.element as HTMLInputElement).checked).valueOf()).toBe(true)
})
it('店铺分类弹窗:「未分类」页签走 ungrouped=true 取行集;「移出分类」按(ids, null)调批量归类', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
jdApi.fetchJdProductList.mockImplementation(() =>
Promise.resolve({ items: [item(1, { groupId: null, groupName: '' })], total: 1, page: 1, pageSize: 20 }))
const wrapper = mount(JdProductGroupDialog, { props: { visible: false }, global: { plugins: [pinia] } })
await wrapper.setProps({ visible: true })
await flushPromises()
await flushPromises()
const listCallsBefore = jdApi.fetchJdProductList.mock.calls.length
await wrapper.findAll('.scope-tabs button').find((b) => b.text() === '未分类')!.trigger('click')
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBe(listCallsBefore + 1, '切「未分类」必须立刻重取')
expect(jdApi.fetchJdProductList.mock.calls.at(-1)![0]).toMatchObject({ ungrouped: true, companyId: null })
await wrapper.findAll('tbody input[type="checkbox"]')[0].setValue(true)
jdApi.batchAssignJdProductGroup.mockResolvedValue(1)
await wrapper.findAll('button').find((b) => b.text() === '移出分类')!.trigger('click')
await flushPromises()
await flushPromises()
expect(jdApi.batchAssignJdProductGroup).toHaveBeenCalledWith([1], null)
})
it('切公司 Tab 重取并清掉上一家的筛选(company-tab-wiring 同口径;分组公共不清)', async () => {
jdApi.fetchJdProductGroups.mockResolvedValue([{ id: 7, name: '甲组', sortOrder: 0, productCount: 3 }])
const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 })
const textInputs = wrapper.findAll('.form-group input[type="text"]')
await textInputs[0].setValue('旗舰自营店')
await textInputs[2].setValue('保温杯')
await wrapper.find('select').setValue('7')
const callsBefore = jdApi.fetchJdProductList.mock.calls.length
useCompanyTabStore().setActiveId(2)
await flushPromises()
await flushPromises()
expect(jdApi.fetchJdProductList.mock.calls.length).toBeGreaterThan(callsBefore)
const last = jdApi.fetchJdProductList.mock.calls.at(-1)![0]
expect(last.companyId).toBe(2)
expect(last.shopName).toBe('', '切公司必须清掉上一家的店铺名')
expect(last.titleKeyword).toBe('', '切公司必须清掉上一家的标题关键字')
expect(last.groupId).toBe('7', '分组全平台一份(公共),groupId 与公司维度正交——切 tab 不清')
expect(last).not.toHaveProperty('category', '切公司必须清掉上一家选的类目')
expect(last.page).toBe(1)
// 分组选项是全局的:切 tab 不重取(首屏那一次之后就不再增长),且任何一次拉取都不带公司维度。
for (const call of jdApi.fetchJdProductGroups.mock.calls) {
expect(call).toEqual([], '分组选项是全局的,任何一次拉取都不带公司维度')
}
})
it('空态与加载失败条(失败给重试,不把整页打死)', async () => {
const empty = await mountWith({ items: [], total: 0, page: 1, pageSize: 20 })
const tip = empty.find('.empty-tip')
expect(tip.exists()).toBe(true)
expect(tip.text()).toContain('暂无京东商品数据')
empty.unmount()
jdApi.fetchJdProductList.mockRejectedValue(new Error('上游 502'))
const failed = mount(JdDatabasePage, { global: { plugins: [pinia] } })
await flushPromises()
await flushPromises()
expect(failed.find('.load-failure-bar').exists()).toBe(true)
expect(failed.find('.load-failure-bar').text()).toContain('京东商品列表加载失败')
})
})