Files
crawler-plugin/admin-frontend-vue/tests/mount/jd-edit-drawer-images.mount.test.ts
T

175 lines
8.0 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.
/**
* 京东商品编辑抽屉「图片区」(2026-11-16 客户口径「删除做成打叉的 icon 放图右上角,
* 也要支持编辑替换本地的图」+替换+新增,B109-01 落地)的挂载契约。
*
* 形态:× 右上角标删(保存时一并删除,遮罩可点撤销);hover 替换条(multipart 立即生效);
* 「+ 新增主图」入口(imageType=MAIN)。objectKey 服务端内容寻址生成——前端只传文件。
* 跑法:`npx vitest run tests/mount/jd-edit-drawer-images.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import JdProductEditDrawer from '@/pages/jd/JdProductEditDrawer.vue'
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(),
uploadJdProductImage: vi.fn(),
batchAssignJdProductGroup: vi.fn(),
}))
const feedbackMock = vi.hoisted(() => vi.fn())
vi.mock('@/pages/jd/jd-product-api.ts', () => jdApi)
vi.mock('@/components/admin-feedback-ui', () => ({ showAdminFeedback: feedbackMock }))
const ITEM = {
id: 9,
shopId: 3,
shopName: '旗舰自营店',
productCode: 'JD-1009',
skuId: 'SKU-9',
itemNum: 'ITEM-9',
skuCount: 12,
healthScore: 81,
title: '304不锈钢保温杯大容量便携',
brand: '锅宝',
categoryPath: '家居 > 厨具 > 保温杯',
priceMin: '12.9',
priceMax: '15.9',
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-9.jpg',
attrCount: 0,
imageCount: 2,
groupId: null,
groupName: '',
syncedAt: '2026-11-12 09:00:00',
}
function image(id: number, imageType: string, url: string) {
return { id, imageType, attrName: null, sortNo: id, url, byteSize: 1024, width: null, height: null }
}
function detailPayload(images: ReturnType<typeof image>[]) {
return { item: ITEM, attrGroups: [], images, skus: [], attrJsonRaw: '' }
}
beforeEach(() => {
vi.clearAllMocks()
jdApi.fetchJdProductGroups.mockResolvedValue([])
})
async function mountWith(images: ReturnType<typeof image>[]): Promise<VueWrapper<Element>> {
jdApi.fetchJdProductDetail.mockResolvedValue(detailPayload(images))
// 抽屉的加载 watch 非 immediate(真实页面里由「点编辑」把 visible 翻真触发):
// 先挂 false 再 setProps 翻真,与生产触发时序同形。
const wrapper = mount(JdProductEditDrawer, {
props: { item: null as typeof ITEM | null, visible: false },
})
await wrapper.setProps({ item: ITEM, visible: true })
await flushPromises()
await flushPromises()
return wrapper
}
/** 把夹具文件塞进隐藏 file input 并触发 change。 */
async function chooseFile(wrapper: VueWrapper<Element>, name = 'a.png'): Promise<File> {
const input = wrapper.find('input[type="file"]')
const file = new File(['x'], name, { type: 'image/png' })
Object.defineProperty(input.element, 'files', { value: [file] })
await input.trigger('change')
await flushPromises()
await flushPromises()
return file
}
describe('京东商品编辑抽屉图片区(×右上角+替换+新增,B109-01)', () => {
it('挂载回填图片区:每格右上角有 × 标记、hover 替换条存在、新增按钮存在(上传/替换暂未开放的旧文案下线)', async () => {
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg'), image(12, 'DETAIL', 'https://img.example/b.jpg')])
const cells = wrapper.findAll('.image-cell')
expect(cells).toHaveLength(2)
expect(cells[0].find('.image-x').exists()).toBe(true, '右上角 × 删除标记')
expect(cells[0].find('.image-replace').exists()).toBe(true, 'hover 替换条')
expect(cells[0].find('.image-marked-mask').exists()).toBe(false, '未标删时无遮罩')
const addBtn = wrapper.find('.btn-add-image')
expect(addBtn.exists()).toBe(true)
expect(addBtn.text()).toContain('新增主图')
expect(wrapper.find('h4').text()).not.toContain('暂未开放', '「上传/替换暂未开放」旧文案下线')
})
it('点 × 标记删除(保存时一并删除):遮罩出现、计数文案更新;再点撤销恢复', async () => {
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg'), image(12, 'MAIN', 'https://img.example/b.jpg')])
await wrapper.find('.image-cell .image-x').trigger('click')
let cell = wrapper.findAll('.image-cell')[0]
expect(cell.classes()).toContain('marked')
expect(cell.find('.image-marked-mask').exists()).toBe(true)
expect(wrapper.find('.delete-count').text()).toContain('已标记删除 1 张')
await cell.find('.image-marked-mask').trigger('click')
cell = wrapper.findAll('.image-cell')[0]
expect(cell.classes()).not.toContain('marked')
expect(wrapper.find('.delete-count').exists()).toBe(false)
expect(jdApi.uploadJdProductImage).not.toHaveBeenCalled()
})
it('hover 替换条选本地图:uploadJdProductImage 带 replaceImageId 调用,立即生效回填新 url 并置 saved', async () => {
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg')])
const clickSpy = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {})
await wrapper.find('.image-cell .image-replace').trigger('click')
expect(clickSpy).toHaveBeenCalled()
jdApi.uploadJdProductImage.mockResolvedValue(detailPayload([image(11, 'MAIN', 'https://img.example/replaced.jpg')]))
const file = await chooseFile(wrapper, 'b.png')
expect(jdApi.uploadJdProductImage).toHaveBeenCalledTimes(1)
expect(jdApi.uploadJdProductImage.mock.calls[0][0]).toBe(9)
expect(jdApi.uploadJdProductImage.mock.calls[0][1]).toBe(file)
expect(jdApi.uploadJdProductImage.mock.calls[0][2]).toEqual({ replaceImageId: 11 })
expect(wrapper.findAll('.image-cell')[0].find('img').attributes('src')).toBe('https://img.example/replaced.jpg')
expect(feedbackMock).toHaveBeenCalledWith(expect.stringContaining('已替换'), 'success')
expect(wrapper.emitted('saved')).toBeTruthy()
clickSpy.mockRestore()
})
it('「+ 新增主图」入口:uploadJdProductImage 带 imageType=MAIN(objectKey 由服务端生成,前端不自造)', async () => {
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg')])
const clickSpy = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {})
await wrapper.find('.btn-add-image').trigger('click')
expect(clickSpy).toHaveBeenCalled()
jdApi.uploadJdProductImage.mockResolvedValue(detailPayload([
image(11, 'MAIN', 'https://img.example/a.jpg'),
image(13, 'MAIN', 'https://img.example/new.jpg'),
]))
await chooseFile(wrapper, 'c.png')
expect(jdApi.uploadJdProductImage.mock.calls[0][2]).toEqual({ imageType: 'MAIN' })
expect(wrapper.findAll('.image-cell')).toHaveLength(2)
expect(feedbackMock).toHaveBeenCalledWith(expect.stringContaining('已新增'), 'success')
clickSpy.mockRestore()
})
it('上传失败:红条出现(requestErrorMessage 对非信封异常回通用文案)、图片区不回填', async () => {
const wrapper = await mountWith([image(11, 'MAIN', 'https://img.example/a.jpg')])
vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {})
await wrapper.find('.btn-add-image').trigger('click')
jdApi.uploadJdProductImage.mockRejectedValue(new Error('单张图片不能超过 10MB'))
await chooseFile(wrapper, 'big.png')
expect(wrapper.find('.drawer-failure').exists()).toBe(true, '失败红条出现')
expect(wrapper.findAll('.image-cell')).toHaveLength(1, '失败不回填')
vi.restoreAllMocks()
})
})