import { defineComponent, h, nextTick, ref, resolveDirective, withDirectives } from 'vue' import { mount } from '@vue/test-utils' import VueDOMPurifyHTML from 'vue-dompurify-html' import { ElMessage, ElMessageBox } from 'element-plus' import { CACHE_KEY, clearLegacyLoginForm, scopedStorageKey, useCache } from '@/hooks/web/useCache' import { useLocalPagination } from '@/hooks/web/useLocalPagination' import { useValidator } from '@/hooks/web/useValidator' import { useMessage } from '@/hooks/web/useMessage' import { useI18n } from '@/hooks/web/useI18n' import { useTitle } from '@/hooks/web/useTitle' import { useDictStore } from '@/store/modules/dict' import { DictTag } from '@/components/DictTag' import { getDictLabel, getDictObj, getIntDictOptions, getStrDictOptions, getBoolDictOptions } from '@/utils/dict' vi.mock('element-plus', async (importOriginal) => { const actual = await importOriginal() return { ...actual, ElMessage: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn() }), ElMessageBox: Object.assign(vi.fn(), { alert: vi.fn().mockResolvedValue('confirm'), confirm: vi.fn().mockResolvedValue('confirm'), prompt: vi.fn().mockResolvedValue({ value: '理由' }) }) } }) describe('hooks/useCache', () => { it('根路径部署时键名不加前缀,读写 localStorage', () => { expect(scopedStorageKey('k')).toBe('k') const { wsCache } = useCache() wsCache.set(CACHE_KEY.LANG, 'zh-CN') expect(wsCache.get(CACHE_KEY.LANG)).toBe('zh-CN') expect(localStorage.getItem(CACHE_KEY.LANG)).toContain('zh-CN') }) it('进入登录页清除旧版“记住密码”缓存的口令', () => { const { wsCache } = useCache() wsCache.set(CACHE_KEY.LoginForm, { username: 'admin', password: 'secret', rememberMe: true }) wsCache.set('loginForm', { password: 'legacy' }) clearLegacyLoginForm() expect(wsCache.get(CACHE_KEY.LoginForm)).toBeNull() expect(wsCache.get('loginForm')).toBeNull() expect(JSON.stringify(localStorage)).not.toContain('secret') }) }) describe('hooks/useLocalPagination', () => { it('按页切片、页码越界纠正、数据变化后重置', () => { const source = ref(Array.from({ length: 25 }, (_, i) => i + 1)) const keyword = ref('') const pager = useLocalPagination(() => source.value, { pageSize: 10, resetOn: [keyword] }) expect(pager.total.value).toBe(25) expect(pager.pageCount.value).toBe(3) expect(pager.rows.value).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) pager.page.value = 3 expect(pager.rows.value).toEqual([21, 22, 23, 24, 25]) pager.page.value = 99 expect(pager.page.value).toBe(3) keyword.value = 'x' expect(pager.page.value).toBe(1) pager.pageSize.value = 0 expect(pager.pageSize.value).toBe(10) source.value = [1] expect(pager.pageCount.value).toBe(1) }) }) describe('hooks/useValidator', () => { const { required, lengthRange, notSpace, notSpecialCharacters } = useValidator() const run = (rule: ReturnType, value: string) => new Promise((resolve) => (rule.validator as (r: unknown, v: string, cb: (e?: Error) => void) => void)({}, value, resolve) ) it('必填与长度规则', () => { expect(required('请输入名称')).toEqual({ required: true, message: '请输入名称' }) expect(lengthRange({ min: 2, max: 8, message: '2-8 位' })).toEqual({ min: 2, max: 8, message: '2-8 位' }) }) it('不允许空格与特殊字符', async () => { expect(await run(notSpace('不能有空格'), 'a b')).toBeInstanceOf(Error) expect(await run(notSpace(), 'ab')).toBeUndefined() expect(await run(notSpecialCharacters('非法'), 'a { it('消息与确认框统一走 element-plus', async () => { const message = useMessage() message.success('保存成功') message.error('失败') expect(ElMessage.success).toHaveBeenCalledWith('保存成功') expect(ElMessage.error).toHaveBeenCalledWith('失败') await message.alertWarning('注意') expect(ElMessageBox.alert).toHaveBeenCalled() }) }) describe('hooks/useI18n 与 useTitle', () => { it('未安装 i18n 时原样返回 key(带命名空间)', () => { expect(useI18n().t('common.ok')).toBe('common.ok') expect(useI18n('login').t('title')).toBe('login.title') }) it('useTitle 同步 document.title', async () => { const title = useTitle() await nextTick() expect(document.title).toBe(title.value) title.value = '财开云平台 - 用户管理' await nextTick() expect(document.title).toBe('财开云平台 - 用户管理') }) }) describe('utils/dict 与 DictTag 组件', () => { beforeEach(() => { const store = useDictStore() store.isSetDict = true store.dictMap = { common_status: [ { value: '0', label: '开启', colorType: 'success', cssClass: '' }, { value: '1', label: '关闭', colorType: 'info', cssClass: '#b7390b' } ], infra_boolean_string: [{ value: 'true', label: '是', colorType: '', cssClass: '' }] } as unknown as Map }) it('字典取值转换', () => { expect(getIntDictOptions('common_status').map((d) => d.value)).toEqual([0, 1]) expect(getStrDictOptions('common_status').map((d) => d.value)).toEqual(['0', '1']) expect(getBoolDictOptions('infra_boolean_string')[0].value).toBe(true) expect(getDictLabel('common_status', 1)).toBe('关闭') expect(getDictObj('common_status', 0)?.colorType).toBe('success') expect(getDictLabel('not_exist', 1)).toBe('') }) it('DictTag 按值渲染标签,支持逗号分隔多值与自定义颜色', () => { const one = mount(DictTag, { props: { type: 'common_status', value: 0 } }) expect(one.text()).toBe('开启') const many = mount(DictTag, { props: { type: 'common_status', value: '0,1' } }) expect(many.findAll('.el-tag')).toHaveLength(2) expect(many.html()).toContain('background-color: rgb(183, 57, 11)') const empty = mount(DictTag, { props: { type: 'common_status', value: '' } }) expect(empty.text()).toBe('') }) }) describe('v-dompurify-html 消毒指令', () => { it('渲染 HTML 时移除脚本与事件处理器', () => { // 与业务模板中 v-dompurify-html 等价的渲染函数写法 const Rendered = defineComponent({ props: { html: { type: String, required: true } }, setup(props) { const purify = resolveDirective('dompurify-html')! return () => withDirectives(h('div', { class: 'box' }), [[purify, props.html]]) } }) const wrapper = mount(Rendered, { props: { html: '加粗链接' }, global: { plugins: [VueDOMPurifyHTML] } }) const html = wrapper.find('.box').html() expect(html).toContain('加粗') expect(html).not.toContain('onerror') expect(html).not.toContain('