/** * 京东数据库页(v1.4 Phase 5)的挂载契约。 * * 形态:panel-box + 筛选行(店铺/商品编码/标题关键字/商品状态/分组/同步起止 date 对)+ * 查询/导出/重置/管理分组 + 自绘明细表(点行开详情抽屉)+ OldPagination; * 公司 tab 切换=清筛选重取(company-tab-wiring 同口径)。 * 不用 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(), exportJdProductList: vi.fn(), deleteJdProducts: vi.fn(), fetchJdProductGroups: vi.fn(), createJdProductGroup: vi.fn(), updateJdProductGroup: vi.fn(), deleteJdProductGroup: 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 = {}) { 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([]) confirmMock.mockResolvedValue(true) }) async function mountWith(payload: unknown): Promise> { 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('行内容只摆部分字段(B104 用户口径「外边列表部分字段」):勾选/主图/标题/编码/货号/品牌/价格/库存/状态/店铺/分组/同步(12 列),其余收进详情抽屉', 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(12) expect(cells[0].find('input[type="checkbox"]').exists()).toBe(true, '第 1 列是勾选框') expect(cells[1].find('.jd-thumb').exists()).toBe(true, '第 2 列是主图') expect(cells[2].text()).toContain('304不锈钢保温杯') expect(cells[3].text()).toBe('JD-1001') expect(cells[4].text()).toBe('ITEM-1', '货号列=京麦后台「货号」') expect(cells[5].text()).toBe('锅宝') expect(cells[6].text()).toBe('12.90 ~ 15.90', '价格区间=min ~ max') expect(cells[7].text()).toBe('500', '总库存列') expect(cells[8].text()).toBe('上架中') expect(cells[9].text()).toBe('旗舰自营店') expect(cells[10].text()).toBe('甲组') expect(cells[11].text()).not.toBe('-', '同步时间格式化展示') // 从列表撤下的字段不许出现在表头(全部收进详情抽屉,见下方抽屉断言)。 const headerText = wrapper.find('thead').text() for (const gone of ['类目', '信息分', 'SKU', '上架时间', '创建时间', '修改时间']) { expect(headerText).not.toContain(gone, `${gone}列已收进详情抽屉,不再上列表`) } expect(wrapper.find('.jd-thumb').exists()).toBe(true, '主图列渲染缩略图') }) it('主图列:有自有桶 URL 才出图,没有就显示「无图」(不拿京东原图域名顶)', async () => { const wrapper = await mountWith({ items: [item(1), item(2, { mainImageUrl: '' })], total: 2, page: 1, pageSize: 20, }) const rowTexts = wrapper.findAll('tbody tr').map((tr) => tr.text()) expect(wrapper.findAll('.jd-thumb')).toHaveLength(1) expect(rowTexts[1]).toContain('无图') }) it('分组读不到的那行展示「未分组」(不猜名字)', 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')[10].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(4, '店铺+商品编码+标题关键字+商品状态四个文本筛选框') await textInputs[0].setValue('旗舰自营店') await textInputs[1].setValue('JD-1001') await textInputs[2].setValue('保温杯') await textInputs[3].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: '保温杯', saleStatus: '上架中', groupId: '7', syncedFrom: '2026-11-01', syncedTo: '2026-11-09', page: 1, companyId: 1, }) }) 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(1) 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('重置把筛选面回空并回第一页重取', 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('导出=当前过滤面全量(含公司 tab 与分组),成功反馈点名落盘文件', async () => { const createObjectURL = vi.fn(() => 'blob:mock-url') const revokeObjectURL = vi.fn() const urlRecord = URL as unknown as Record Object.defineProperty(URL, 'createObjectURL', { value: createObjectURL, configurable: true, writable: true }) Object.defineProperty(URL, 'revokeObjectURL', { value: revokeObjectURL, configurable: true, writable: true }) const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) jdApi.exportJdProductList.mockImplementation(() => Promise.resolve({ blob: new Blob(['xlsx']), filename: '京东数据库-20261114090000.xlsx' }), ) try { const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 }) const btn = wrapper.findAll('button').find((b) => b.text() === '导出') expect(btn, '筛选行必须有「导出」按钮').toBeTruthy() await btn!.trigger('click') await flushPromises() await flushPromises() expect(jdApi.exportJdProductList).toHaveBeenCalledTimes(1) const call = jdApi.exportJdProductList.mock.calls[0][0] expect(call).toMatchObject({ shopName: '', groupId: '', companyId: 1 }) expect(createObjectURL).toHaveBeenCalledTimes(1) expect(clickSpy).toHaveBeenCalled() expect(document.body.textContent).toContain('已导出', '成功反馈点名落盘文件') } finally { Object.defineProperty(URL, 'createObjectURL', { value: undefined, configurable: true, writable: true }) Object.defineProperty(URL, 'revokeObjectURL', { value: undefined, configurable: true, writable: true }) clickSpy.mockRestore() } }) it('导出失败把服务端业务文案弹出来,不许静默;在途标记复位', async () => { jdApi.exportJdProductList.mockImplementation(() => Promise.reject(new Error('京东商品共 80001 行,超过导出上限 50000 行,请缩小筛选范围后重试'))) const wrapper = await mountWith({ items: [item(1)], total: 1, page: 1, pageSize: 20 }) await wrapper.findAll('button').find((b) => b.text() === '导出')!.trigger('click') await flushPromises() await flushPromises() expect(document.body.textContent).toContain('超过导出上限') const btn = wrapper.findAll('button').find((b) => b.text() === '导出') expect(btn!.text()).toBe('导出', '失败后在途标记必须复位') expect((btn!.element as HTMLButtonElement).disabled).toBe(false) }) it('点行打开详情抽屉:按 (id, companyId) 取详情,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, 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:从列表撤下的字段(类目/SKU 数/京东创建/修改时间)+店铺/分组,详情里全量可见。 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('删除:勾选两行点删除 → 二次确认点名数量与桶清理 → 批量端点带 (ids, companyId),成功后刷新并清勾选', 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], 1) 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) // 打开弹窗 = 拉一次分组列表(第 2 次:首屏已拉过一次) expect(jdApi.fetchJdProductGroups).toHaveBeenCalledTimes(2) expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(1) // 模拟分组管理里删了一个分组: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('切公司 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('', '切公司必须清掉上一家选的分组') expect(last.page).toBe(1) expect(jdApi.fetchJdProductGroups).toHaveBeenLastCalledWith(2) }) 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('京东商品列表加载失败') }) })