Files
crawler-plugin/admin-frontend-vue/tests/mount/records-select-el.mount.test.ts
T
huangzd1997 7299166e96 style(admin): 全站原生下拉统一换 el-select——弹层圆角与亚马逊面一致(2026-11-17 用户口径「样式咋不是圆角 和亚马逊不统一 其他地方也要看看」)
范围:src 里原生 <select> 由 36 处清零(含全站共享分页条),15 个页面 + 1 个组件。
换法统一:class="admin-filter"(main.css 皮肤 42px/9px/#f8fbfd/focus ring)+
aria-label 定位 + el-option 显式 label;「全部 XX」空值行与 value 形状逐字保留
('' / null / String(id) / '1'/'0' / `${source}|${deviceId}` 等,下游查询参数与后端枚举不动)。

- OldPagination:每页条数下拉换 el-select(局部 import,挂载测试单 mount 也能渲染),壳压回分页条 30px/8px 档
- account 三页(菜单类型/密钥状态/分组)+ GroupsPage/UsersPage 清死 select 规则
- asin 三页(国家/弹窗分组):弹窗分组用 placeholder+clearable+:value-on-clear 钉回 null,守 number|null 契约
- patent 页(国家/分组)
- records 两页(来源/用户/终端覆盖):终端覆盖 value 仍 source|deviceId
- tasks 四页 + 任务看板(业务/状态/类型/来源/店铺/分组/场景):BrandGating/DuplicateCheck/KeywordUsage 三页本地是 34px 紧凑档,
  故把 el-select 壳压回本地 34px/7px 与同行输入框齐高(否则高 8px 错位)

测试:mount 全量 21 文件 164 passed;node --test 1924 例 1922 passed(2 红为在册:
date-range-order 环境红、company-config-entry-super-only 由 ee613db0 引入与本次无关);
vue-tsc rc=0。新增 account-select-el / records-select-el 两支换壳契约(值形状 + 空值行 + 点开→点选项)。
2026-11-17 13:49:39 +08:00

216 lines
10 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.
/**
* 日志管理页 / 生成记录页的原生 <select> → el-select(2026-11-17 用户口径「和亚马逊不统一」:
* 原生 select 的弹层是浏览器直角原生物 ⇒ 换 EP 圆角弹层,外壳走全局 .admin-filter)。
*
* 这里钉住换壳时最容易错的两件事:
* 1. **值形状逐字不变**——「全部来源」/「全部用户」空行仍是 ''、用户仍是 String(id)、
* 终端仍是 `${source}|${deviceId}`、模式仍是 'full'/'selected' 常量(后端按这些字符串解析,
* 形状一动就错单,而界面上看起来只是"选了个下拉");
* 2. **选中 → 落参的链路仍只有一处**——来源 source、用户 Number(uid)、终端 '|' 切分与 mode 常量。
*
* aria-label 经 EP 的 ariaLabel prop 落在内层 combobox input 上,选项清单走组件树读
* (弹层 teleport 到 body),点选走「点开→点选项」真实路径。
* 不用 readFileSync(source-pin-ratchet 对台账外新文件带读点即红),全部走真实挂载断言。
*
* 跑法:`npx vitest run tests/mount/records-select-el.mount.test.ts`
*/
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createPinia, setActivePinia, type Pinia } from 'pinia'
import { defineComponent, h } from 'vue'
import { ElOption, ElSelect } from 'element-plus'
import DeviceLogsPage from '@/pages/records/DeviceLogsPage.vue'
import RecordsHistoryPage from '@/pages/records/RecordsHistoryPage.vue'
import { useAdminSessionStore } from '@/stores/admin-session'
const deviceLogsApi = vi.hoisted(() => ({
fetchDeviceLogFiles: vi.fn(),
fetchDeviceLogContent: vi.fn(),
fetchDeviceLogConfig: vi.fn(),
fetchDeviceLogDevices: vi.fn(),
deviceLogDownloadUrl: vi.fn((id: number) => `/api/admin/device-logs/${id}/download`),
deleteDeviceLogFile: vi.fn(),
deleteDeviceLogOverride: vi.fn(),
updateDeviceLogGlobalMode: vi.fn(),
updateDeviceLogOverride: vi.fn(),
}))
const historyApi = vi.hoisted(() => ({
fetchHistoryList: vi.fn(),
fetchHistoryUserOptions: vi.fn(),
}))
vi.mock('@/api/device-logs', () => deviceLogsApi)
vi.mock('@/pages/records/history-api.ts', () => historyApi)
/** 采集配置弹窗(el-dialog)用桩:真实 dialog 把内容 teleport 到 body,wrapper 里就查不到;
* 桩只留一层 div 并把默认插槽摊在挂载树里,modelValue 与真实一样控制开关。 */
const DialogStub = defineComponent({
name: 'ElDialogStub',
props: { modelValue: { type: Boolean, default: false } },
setup(props, { slots }) {
return () => (props.modelValue ? h('div', { class: 'dialog-stub' }, slots.default?.()) : null)
},
})
// ---------------- el-select 交互助手(与京东数据库页/亚马逊面同一套口径) ----------------
/** 按 aria-label 找对应的 ElSelect 组件实例(页面里还有 OldPagination 的「每页条数」,靠 aria-label 区分)。 */
function selectByLabel(wrapper: VueWrapper<Element>, label: string) {
const found = wrapper.findAllComponents(ElSelect).find((s) => s.find(`[aria-label="${label}"]`).exists())
expect(found, `应存在 aria-label="${label}" 的下拉`).toBeTruthy()
return found!
}
/** 读某颗下拉的全部选项文案(label prop;组件树查询不受弹层 teleport 影响)。 */
function optionLabels(wrapper: VueWrapper<Element>, label: string): string[] {
return selectByLabel(wrapper, label).findAllComponents(ElOption).map((o) => o.props('label') as string)
}
/** 读某颗下拉的全部选项 value(形状判据:空串/字符串 id/`source|deviceId`/mode 常量)。 */
function optionValues(wrapper: VueWrapper<Element>, label: string): unknown[] {
return selectByLabel(wrapper, label).findAllComponents(ElOption).map((o) => o.props('value'))
}
/** 点开指定下拉并点选目标文案的选项(触发 update:modelValue + change,与真实用户一致)。
* 面板按内层 input 的 aria-controls 圈定,避免另一颗(可能仍挂着的)弹层串台。 */
async function pickSelectOption(wrapper: VueWrapper<Element>, label: string, optionText: string): Promise<void> {
const input = wrapper.get(`[aria-label="${label}"]`)
await input.trigger('click')
await flushPromises()
const contentId = input.attributes('aria-controls')
const scope = (contentId && document.getElementById(contentId)) ?? document.body
const items = [...scope.querySelectorAll('.el-select-dropdown__item')].filter((el) => !el.classList.contains('is-hidden'))
const target = items.find((el) => (el.textContent ?? '').trim() === optionText)
expect(target, `下拉应弹出「${optionText}」选项`).toBeTruthy()
await new DOMWrapper(target as Element).trigger('click')
await flushPromises()
}
/** 按文案点按钮(筛选条上的查询/重置、弹窗里的添加/更新覆盖)。 */
async function clickButton(wrapper: VueWrapper<Element>, text: string): Promise<void> {
const button = wrapper.findAll('button').find((b) => b.text().trim() === text)
expect(button, `应存在「${text}」按钮`).toBeTruthy()
await button!.trigger('click')
await flushPromises()
await flushPromises()
}
/** 最近一次调用的入参(首屏 + 公司 tab watch 可能各发一次,判"选完落什么参"只认最后一次)。 */
function lastArgs(fn: { mock: { calls: unknown[][] } }): Record<string, unknown> {
const calls = fn.mock.calls
expect(calls.length, '接口应至少被调用一次').toBeGreaterThan(0)
return calls[calls.length - 1][0] as Record<string, unknown>
}
const USERS = [
{ id: 7, username: '张三' },
{ id: 8, username: '李四' },
]
let pinia: Pinia
beforeEach(() => {
vi.clearAllMocks()
pinia = createPinia()
setActivePinia(pinia)
useAdminSessionStore().user = { id: 1, username: 'root', role: 'super_admin' }
historyApi.fetchHistoryUserOptions.mockResolvedValue(USERS)
})
async function mountDeviceLogs(): Promise<VueWrapper<Element>> {
deviceLogsApi.fetchDeviceLogFiles.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 15, retentionDays: 7 })
deviceLogsApi.fetchDeviceLogConfig.mockResolvedValue({ globalMode: 'full', overrides: [] })
deviceLogsApi.fetchDeviceLogDevices.mockResolvedValue([
{ source: 'client', deviceId: 'dev-1', deviceName: '工位A', lastUploadAt: null },
])
const wrapper = mount(DeviceLogsPage, {
global: { plugins: [pinia, ElSelect, ElOption], stubs: { ElDialog: DialogStub } },
})
await flushPromises()
await flushPromises()
return wrapper
}
describe('日志管理页 × el-select', () => {
it('筛选条两颗下拉:空行/字符串 id/来源常量逐字不变', async () => {
const wrapper = await mountDeviceLogs()
expect(optionLabels(wrapper, '来源')).toEqual(['全部来源', '桌面客户端', '麦象采集机'])
expect(optionValues(wrapper, '来源')).toEqual(['', 'client', 'maixiang'])
// 用户清单很长 ⇒ filterable;值仍是 String(id)(下游 `uidFilter.value ? Number(...)` 判空)
expect(selectByLabel(wrapper, '指定用户').props('filterable')).toBe(true)
expect(optionLabels(wrapper, '指定用户')).toEqual(['全部用户', '张三', '李四'])
expect(optionValues(wrapper, '指定用户')).toEqual(['', '7', '8'])
wrapper.unmount()
})
it('选中来源/用户后查询:source 走常量、uid 仍是数字', async () => {
const wrapper = await mountDeviceLogs()
await pickSelectOption(wrapper, '来源', '麦象采集机')
await pickSelectOption(wrapper, '指定用户', '李四')
await clickButton(wrapper, '查询')
const args = lastArgs(deviceLogsApi.fetchDeviceLogFiles)
expect(args.source).toBe('maixiang')
expect(args.uid).toBe(8)
expect(typeof args.uid).toBe('number')
wrapper.unmount()
})
it('重置回到空值首行:不发 source、不发 uid(空串的「全部」语义不变)', async () => {
const wrapper = await mountDeviceLogs()
await pickSelectOption(wrapper, '来源', '桌面客户端')
await pickSelectOption(wrapper, '指定用户', '张三')
await clickButton(wrapper, '重置')
const args = lastArgs(deviceLogsApi.fetchDeviceLogFiles)
expect(args.source).toBeUndefined()
expect(args.uid).toBeUndefined()
wrapper.unmount()
})
it('采集配置弹窗:终端值仍是 `source|deviceId`、模式仍是 full/selected 常量', async () => {
const wrapper = await mountDeviceLogs()
await clickButton(wrapper, '采集配置')
expect(optionLabels(wrapper, '选择终端')).toEqual(['选择终端(最近上报的设备)', '桌面客户端 · 工位A(dev-1)'])
expect(optionValues(wrapper, '选择终端')).toEqual(['', 'client|dev-1'])
expect(optionLabels(wrapper, '覆盖模式')).toEqual(['全量采集', '精选采集'])
expect(optionValues(wrapper, '覆盖模式')).toEqual(['full', 'selected'])
await pickSelectOption(wrapper, '选择终端', '桌面客户端 · 工位A(dev-1)')
await pickSelectOption(wrapper, '覆盖模式', '全量采集')
await clickButton(wrapper, '添加/更新覆盖')
expect(deviceLogsApi.updateDeviceLogOverride).toHaveBeenCalledWith('client', 'dev-1', '工位A', 'full')
wrapper.unmount()
})
})
describe('生成记录页 × el-select', () => {
async function mountHistory(): Promise<VueWrapper<Element>> {
historyApi.fetchHistoryList.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 10 })
const wrapper = mount(RecordsHistoryPage, { global: { plugins: [pinia, ElSelect, ElOption] } })
await flushPromises()
await flushPromises()
return wrapper
}
it('指定用户下拉:空行 + String(id) 值形状不变', async () => {
const wrapper = await mountHistory()
expect(selectByLabel(wrapper, '指定用户').props('filterable')).toBe(true)
expect(optionLabels(wrapper, '指定用户')).toEqual(['全部用户', '张三', '李四'])
expect(optionValues(wrapper, '指定用户')).toEqual(['', '7', '8'])
wrapper.unmount()
})
it('选用户查询发数字 userId;选回「全部用户」不发 userId', async () => {
const wrapper = await mountHistory()
await pickSelectOption(wrapper, '指定用户', '李四')
await clickButton(wrapper, '查询')
expect(lastArgs(historyApi.fetchHistoryList).userId).toBe(8)
await pickSelectOption(wrapper, '指定用户', '全部用户')
await clickButton(wrapper, '查询')
expect(lastArgs(historyApi.fetchHistoryList).userId).toBeUndefined()
wrapper.unmount()
})
})