feat: 资产管理前端从管理端拆分为独立工程
CI / build-and-test (push) Canceled after 0s

以 ckcloudManage a44810c 为基础,只保留资产页面(台账、单据、基础数据、同步任务)、
登录/错误/个人资料等公共页面,以及资产单据“查看流程”用到的流程详情页;
统一登录应用编码默认 CK_ASSET,标题“资产管理”,本地端口 9090。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 03:44:26 -08:00
co-authored by Claude Opus 5.5
commit 2072c6780f
713 changed files with 96036 additions and 0 deletions
+157
View File
@@ -0,0 +1,157 @@
import { flushPromises, mount, shallowMount } from '@vue/test-utils'
import type { Component } from 'vue'
import { appPlugins, loginAsAdmin, mockBackend } from '../helpers/app'
/**
* 组件冒烟测试:逐个挂载 src/components 与 src/layout 下的组件(子组件浅渲染),
* 走真实的 request 封装(网络层替换为空数据),断言能渲染出 DOM 且不抛异常。
* 用于发现导入错误、setup 运行时异常、模板引用了不存在的变量等回归。
*/
const pages = import.meta.glob<{ default: Component }>('/src/{components,layout}/**/*.vue')
interface SmokeOptions {
/** 必填 props 的最小合法值 */
props?: Record<string, unknown>
/** 父组件通过 provide 注入的数据 */
provide?: Record<string, unknown>
/** 通过 ref 调用子组件方法的页面需完整渲染子组件 */
deep?: boolean
/** 默认插槽内容 */
slots?: Record<string, string>
/** 无法在 jsdom 中渲染的页面,写明原因 */
skip?: string
}
const node = (type: number, extra: Record<string, unknown> = {}) => ({
id: `node-${type}`,
name: '节点',
type,
showText: '',
conditionNodes: [],
...extra
})
const options: Record<string, SmokeOptions> = {
'/src/components/DictTag/src/DictTag.vue': { props: { type: 'common_status', value: 0 } },
'/src/components/MarkdownView/index.vue': { props: { content: '# 标题\n\n正文' } },
'/src/components/Highlight/src/Highlight.vue': { slots: { default: '财开云平台' } },
'/src/components/Echart/src/Echart.vue': { skip: 'echarts 依赖 canvas,jsdom 不支持' },
'/src/components/Qrcode/src/Qrcode.vue': { skip: '二维码绘制依赖 canvas,jsdom 不支持' },
'/src/components/Cropper/src/CopperModal.vue': { skip: '裁剪依赖 canvas 与 cropperjs,jsdom 不支持' },
'/src/components/Cropper/src/CropperAvatar.vue': { skip: '裁剪依赖 canvas 与 cropperjs,jsdom 不支持' },
'/src/components/PublicView/src/PublicView.vue': {
deep: true,
props: {
columns: [{ label: '名称', field: 'name' }],
request: () => Promise.resolve({ list: [{ name: '张三' }], total: 1 })
}
},
'/src/components/PublicView/src/components/PublicViewSearch.vue': {
props: {
columns: [{ label: '名称', field: 'name' }],
params: {},
config: { defaultCollapsed: false, labelWidth: 'auto', span: 6, showReset: true, collapseRows: 1 },
fieldOptions: {},
fieldLoading: {},
fieldDisabled: {}
}
},
'/src/components/PublicView/src/components/PublicViewSearchField.vue': {
props: { column: { label: '名称', field: 'name', valueType: 'input' }, modelValue: '' }
},
'/src/components/PublicView/src/components/PublicViewTable.vue': {
props: {
columns: [{ label: '名称', field: 'name' }],
data: [{ name: '张三' }],
loading: false,
config: { height: undefined, border: true, stripe: false, rowKey: 'id', selection: false, index: false },
hasRequested: true
}
},
'/src/components/PublicView/src/components/PublicViewTableColumn.vue': {
props: { column: { label: '名称', field: 'name' } }
},
'/src/components/PublicView/src/components/PublicViewTabs.vue': {
props: { tabs: [{ label: '全部', value: 'all' }], activeTab: 'all' }
},
'/src/components/PublicView/src/components/PublicViewToolbar.vue': {
props: { tools: [{ label: '新增', key: 'add' }], selection: [] }
},
'/src/components/SimpleProcessDesignerV2/src/SimpleProcessDesigner.vue': {
skip: '依赖完整模型数据与表单字段注入,在流程模型编辑页中浏览器回归'
},
'/src/components/SimpleProcessDesignerV2/src/nodes-config/UserTaskNodeConfig.vue': {
props: { flowNode: node(11) }
},
'/src/components/SimpleProcessDesignerV2/src/nodes-config/components/HttpRequestSetting.vue': {
props: {
setting: { url: '', header: [], body: [], response: [] },
responseEnable: true,
formItemPrefix: 'httpRequestSetting'
}
},
'/src/components/SimpleProcessDesignerV2/src/nodes/ChildProcessNode.vue': { props: { flowNode: node(20) } },
'/src/components/SimpleProcessDesignerV2/src/nodes/CopyTaskNode.vue': { props: { flowNode: node(12) } },
'/src/components/SimpleProcessDesignerV2/src/nodes/DelayTimerNode.vue': { props: { flowNode: node(14) } },
'/src/components/SimpleProcessDesignerV2/src/nodes/ExclusiveNode.vue': { props: { flowNode: node(51) } },
'/src/components/SimpleProcessDesignerV2/src/nodes/InclusiveNode.vue': { props: { flowNode: node(53) } },
'/src/components/SimpleProcessDesignerV2/src/nodes/ParallelNode.vue': { props: { flowNode: node(52) } },
'/src/components/SimpleProcessDesignerV2/src/nodes/RouterNode.vue': { props: { flowNode: node(54) } },
'/src/components/SimpleProcessDesignerV2/src/nodes/StartUserNode.vue': { props: { flowNode: node(10) } },
'/src/components/SimpleProcessDesignerV2/src/nodes/TriggerNode.vue': { props: { flowNode: node(15) } },
'/src/components/SimpleProcessDesignerV2/src/nodes/UserTaskNode.vue': { props: { flowNode: node(11) } },
'/src/components/bpmnProcessDesigner/package/designer/ProcessDesigner.vue': { skip: '依赖 bpmn-js 建模器实例(window.bpmnInstances),需在流程设计器中浏览器回归' },
'/src/components/bpmnProcessDesigner/package/penal/signal-message/SignalAndMessage.vue': { skip: '依赖 bpmn-js 建模器实例(window.bpmnInstances),需在流程设计器中浏览器回归' },
'/src/components/bpmnProcessDesigner/package/penal/task/ElementTask.vue': { skip: '依赖 bpmn-js 建模器实例(window.bpmnInstances),需在流程设计器中浏览器回归' },
'/src/components/bpmnProcessDesigner/package/penal/task/task-components/ReceiveTask.vue': { skip: '依赖 bpmn-js 建模器实例(window.bpmnInstances),需在流程设计器中浏览器回归' },
'/src/components/bpmnProcessDesigner/package/penal/task/task-components/ScriptTask.vue': { skip: '依赖 bpmn-js 建模器实例(window.bpmnInstances),需在流程设计器中浏览器回归' },
'/src/components/bpmnProcessDesigner/package/penal/task/task-components/ServiceTask.vue': { skip: '依赖 bpmn-js 建模器实例(window.bpmnInstances),需在流程设计器中浏览器回归' },
'/src/components/bpmnProcessDesigner/package/penal/task/task-components/UserTask.vue': { skip: '依赖 bpmn-js 建模器实例(window.bpmnInstances),需在流程设计器中浏览器回归' },
'/src/components/bpmnProcessDesigner/package/penal/flow-condition/FlowCondition.vue': {
skip: '依赖 bpmn-js 建模器实例(window.bpmnInstances),需在流程设计器中浏览器回归'
},
'/src/layout/components/TagsView/src/TagsView.vue': { skip: '依赖真实路由表与当前路由,在布局中浏览器回归' },
'/src/layout/components/Breadcrumb/src/Breadcrumb.vue': { skip: '依赖真实路由表与当前路由,在布局中浏览器回归' },
'/src/layout/components/CkyunHeader.vue': { props: { modules: [], activeModule: undefined } }
}
const entries = Object.keys(pages)
.sort()
.filter((path) => !options[path]?.skip)
describe('components / layout 冒烟渲染', () => {
it('跳过的页面都写明了原因', () => {
for (const [path, option] of Object.entries(options)) {
expect(Object.keys(pages)).toContain(path)
if (option.skip !== undefined) expect(option.skip.length).toBeGreaterThan(5)
}
})
beforeEach(async () => {
await loginAsAdmin()
})
it.each(entries)('%s', async (path) => {
mockBackend()
const errors: unknown[] = []
const mod = await pages[path]()
const option = options[path] ?? {}
const wrapper = (option.deep ? mount : shallowMount)(mod.default, {
props: option.props,
slots: option.slots,
global: {
plugins: appPlugins(),
provide: option.provide,
config: {
errorHandler: (err) => {
errors.push(err)
}
}
}
})
await flushPromises()
expect(errors).toEqual([])
expect(wrapper.html().length).toBeGreaterThan(0)
wrapper.unmount()
})
})
+203
View File
@@ -0,0 +1,203 @@
import { Blob as NodeBlob } from 'node:buffer'
import axios, { type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { ElMessage, ElNotification } from 'element-plus'
import request from '@/config/axios'
import { service } from '@/config/axios/service'
import { getAuthSession, setToken, withAuthSessionLock } from '@/utils/auth'
import type { TokenType } from '@/api/login/types'
vi.mock('element-plus', async (importOriginal) => {
const actual = await importOriginal<typeof import('element-plus')>()
return {
...actual,
ElMessage: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn() }),
ElNotification: Object.assign(vi.fn(), { error: vi.fn(), info: vi.fn() }),
ElMessageBox: Object.assign(vi.fn(), { alert: vi.fn().mockResolvedValue(undefined) })
}
})
vi.mock('@/utils/sessionReplaced', () => ({
checkSessionReplaced: vi.fn().mockResolvedValue(false),
isSessionReplacedNoticeOpen: vi.fn().mockReturnValue(false),
showSessionReplacedNotice: vi.fn().mockResolvedValue(undefined)
}))
const token = (access: string, refresh = 'refresh-1'): TokenType => ({
id: 1,
accessToken: access,
refreshToken: refresh,
userId: 1,
userType: 2,
clientId: 'ckcloud',
expiresTime: Date.now() + 60_000
})
const login = (access = 'access-1', refresh = 'refresh-1') =>
withAuthSessionLock(() => setToken(token(access, refresh), 'session-1'))
type Responder = (config: InternalAxiosRequestConfig) => Partial<AxiosResponse> | Promise<Partial<AxiosResponse>>
/** 用自定义 adapter 代替网络层,记录每次请求的配置 */
const mockAdapter = (responder: Responder) => {
const calls: InternalAxiosRequestConfig[] = []
const adapter: AxiosAdapter = async (config) => {
calls.push(config)
const partial = await responder(config)
return {
status: 200,
statusText: 'OK',
headers: {},
config,
request: { responseType: config.responseType },
data: undefined,
...partial
} as AxiosResponse
}
service.defaults.adapter = adapter
return calls
}
describe('config/axios 请求封装', () => {
it('携带访问令牌,GET 禁用缓存,成功时返回 data 字段', async () => {
await login()
const calls = mockAdapter(() => ({ data: { code: 200, data: { id: 7 } } }))
const result = await request.get<{ id: number }>({ url: '/system/user/get', params: { id: 7 } })
expect(result).toEqual({ id: 7 })
expect(calls[0].headers.Authorization).toBe('Bearer access-1')
expect(calls[0].headers['Cache-Control']).toBe('no-cache')
expect(calls[0].params).toEqual({ id: 7 })
})
it('白名单接口与 isToken=false 不带令牌', async () => {
await login()
const calls = mockAdapter(() => ({ data: { code: 200, data: true } }))
await request.post({ url: '/system/auth/login', data: {} })
await request.get({ url: '/public', headers: { isToken: false } })
expect(calls[0].headers.Authorization).toBeUndefined()
expect(calls[1].headers.Authorization).toBeUndefined()
})
it('表单编码的 POST 自动序列化请求体', async () => {
await login()
const calls = mockAdapter(() => ({ data: { code: 200, data: null } }))
await request.post({
url: '/x',
data: { a: 1, b: 'c' },
headersType: 'application/x-www-form-urlencoded'
})
expect(calls[0].data).toBe('a=1&b=c')
})
it('业务错误码:500 提示通用错误,403 提示刷新,其他码通知后台消息', async () => {
await login()
mockAdapter((config) => {
if (config.url === '/e500') return { data: { code: 500, msg: '内部错误' } }
if (config.url === '/e403') return { data: { code: 403, msg: '没有权限' } }
return { data: { code: 1002, msg: '用户名已存在' } }
})
await expect(request.get({ url: '/e500' })).rejects.toThrow('内部错误')
expect(ElMessage.error).toHaveBeenCalled()
await expect(request.get({ url: '/e403' })).rejects.toMatchObject({ status: 403 })
expect(ElNotification.error).toHaveBeenCalledWith({ title: '没有权限,权限可能已调整,请刷新页面' })
await expect(request.get({ url: '/e1002' })).rejects.toThrow('用户名已存在')
expect(ElNotification.error).toHaveBeenCalledWith({ title: '用户名已存在' })
})
it('无后台消息时按错误码表兜底', async () => {
await login()
mockAdapter(() => ({ data: { code: 404 } }))
await expect(request.get({ url: '/missing' })).rejects.toThrow('访问资源不存在')
})
it('401 时用刷新令牌续期并以新令牌重试原请求', async () => {
await login('old-access', 'refresh-1')
// 后端续期只换发访问令牌,刷新令牌保持不变
const post = vi.spyOn(axios, 'post').mockResolvedValue({
data: { code: 0, data: token('new-access', 'refresh-1') }
})
const calls = mockAdapter((config) =>
config.headers.Authorization === 'Bearer new-access'
? { data: { code: 200, data: 'ok' } }
: { data: { code: 401, msg: '未登录' } }
)
await expect(request.get({ url: '/system/user/page' })).resolves.toBe('ok')
expect(post).toHaveBeenCalledOnce()
expect(post.mock.calls[0][0]).toContain('/system/auth/refresh-token')
expect(post.mock.calls[0][2]?.params).toEqual({ refreshToken: 'refresh-1' })
expect(calls).toHaveLength(2)
expect(getAuthSession()).toMatchObject({ accessToken: 'new-access', refreshToken: 'refresh-1' })
})
it('并发 401 只续期一次', async () => {
await login('old-access', 'refresh-1')
const post = vi.spyOn(axios, 'post').mockImplementation(
() =>
new Promise((resolve) =>
setTimeout(() => resolve({ data: { code: 200, data: token('new-access', 'refresh-1') } }), 5)
)
)
mockAdapter((config) =>
config.headers.Authorization === 'Bearer new-access'
? { data: { code: 200, data: config.url } }
: { data: { code: 401 } }
)
const results = await Promise.all([
request.get({ url: '/a' }),
request.get({ url: '/b' }),
request.get({ url: '/c' })
])
expect(results).toEqual(['/a', '/b', '/c'])
expect(post).toHaveBeenCalledTimes(1)
})
it('刷新令牌失效时清除本地会话并拒绝请求', async () => {
await login('old-access', 'refresh-1')
vi.spyOn(axios, 'post').mockResolvedValue({ data: { code: 401, msg: '刷新令牌已过期' } })
mockAdapter(() => ({ data: { code: 401 } }))
await expect(request.get({ url: '/x' })).rejects.toThrow('登录状态已失效,请重新登录')
await vi.waitFor(() => expect(getAuthSession().accessToken).toBe(''))
})
it('skipAuthRefresh 的 401 直接失败,不续期', async () => {
await login()
const post = vi.spyOn(axios, 'post')
mockAdapter(() => ({ data: { code: 401, msg: '未登录' } }))
await expect(request.get({ url: '/x', skipAuthRefresh: true })).rejects.toThrow('未登录')
expect(post).not.toHaveBeenCalled()
})
it('下载:二进制响应原样返回,JSON 错误体按业务错误处理', async () => {
await login()
const file = new Blob(['a,b'], { type: 'application/vnd.ms-excel' })
mockAdapter((config) =>
config.url === '/export-ok'
? { data: file }
: {
// 用 Node 的 Blob,便于源码中 new Response(blob).json() 读取(jsdom 的 Blob 不被 undici 识别)
data: new NodeBlob([JSON.stringify({ code: 1001, msg: '导出失败' })], {
type: 'application/json'
})
}
)
await expect(request.download({ url: '/export-ok' })).resolves.toBe(file)
await expect(request.download({ url: '/export-bad' })).rejects.toThrow('导出失败')
})
it('网络异常与超时给出中文提示', async () => {
await login()
service.defaults.adapter = async () => {
throw new axios.AxiosError('timeout of 30000ms exceeded', 'ECONNABORTED')
}
await expect(request.get({ url: '/slow' })).rejects.toThrow('timeout')
expect(ElMessage.error).toHaveBeenCalled()
})
it('会话已被其他标签页替换时拒绝旧请求结果', async () => {
await login('access-1', 'refresh-1')
mockAdapter(async () => {
await withAuthSessionLock(() => setToken(token('access-2', 'refresh-9'), 'session-2'))
return { data: { code: 200, data: 'stale' } }
})
await expect(request.get({ url: '/x' })).rejects.toThrow('登录会话已变更')
})
})
+102
View File
@@ -0,0 +1,102 @@
import type { App, Plugin } from 'vue'
import type { AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { createMemoryHistory, createRouter, type Router } from 'vue-router'
import VueDOMPurifyHTML from 'vue-dompurify-html'
import { setupAuth, setupMountedFocus } from '@/directives'
import { setupElementPlus } from '@/plugins/elementPlus'
import { setupGlobCom } from '@/components'
import { service } from '@/config/axios/service'
import { useUserStore } from '@/store/modules/user'
import { getAuthSession, setToken, withAuthSessionLock } from '@/utils/auth'
export interface RecordedRequest {
method: string
url: string
params?: unknown
data?: unknown
}
export type Responder = (request: RecordedRequest) => unknown
/** 分页接口返回空页,其余返回空数组;可按 URL 定制 */
export const defaultResponder: Responder = (request) =>
/page|list-page/i.test(request.url) ? { list: [], total: 0 } : []
/**
* 以 axios adapter 替换网络层:业务代码走真实的 request 封装与拦截器,
* 只把响应换成测试数据,并记录发出的请求。
*/
export const mockBackend = (responder: Responder = defaultResponder) => {
const requests: RecordedRequest[] = []
service.defaults.adapter = async (config: InternalAxiosRequestConfig) => {
const request: RecordedRequest = {
method: (config.method || 'get').toUpperCase(),
url: config.url || '',
params: config.params,
data: typeof config.data === 'string' ? safeJson(config.data) : config.data
}
requests.push(request)
return {
status: 200,
statusText: 'OK',
headers: {},
config,
request: { responseType: config.responseType },
data: { code: 200, data: responder(request), msg: '' }
} as AxiosResponse
}
return requests
}
const safeJson = (value: string) => {
try {
return JSON.parse(value)
} catch {
return value
}
}
/** 已登录、拥有全部权限的管理员会话 */
export const loginAsAdmin = async () => {
if (!getAuthSession().accessToken) {
await withAuthSessionLock(() =>
setToken(
{
id: 1,
accessToken: 'test-access',
refreshToken: 'test-refresh',
userId: 1,
userType: 2,
clientId: 'ckcloud',
expiresTime: 0
},
'test-session'
)
)
}
const userStore = useUserStore()
userStore.permissions = new Set(['*:*:*'])
userStore.roles = ['super_admin']
userStore.user = { id: 1, avatar: '', nickname: '管理员', deptId: 1 }
userStore.isSetUser = true
}
export const createTestRouter = (): Router =>
createRouter({
history: createMemoryHistory(),
routes: [{ path: '/:pathMatch(.*)*', name: 'any', component: { render: () => null } }]
})
/** 与 main.ts 一致的全局注册(不含 i18n / 打印等与渲染无关的插件) */
export const appPlugins = (router: Router = createTestRouter()): Plugin[] => [
router,
VueDOMPurifyHTML,
{
install(app: App) {
setupElementPlus(app)
setupGlobCom(app)
setupAuth(app)
setupMountedFocus(app)
}
}
]
+172
View File
@@ -0,0 +1,172 @@
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<typeof import('element-plus')>()
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<typeof notSpace>, value: string) =>
new Promise<Error | undefined>((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<b')).toBeInstanceOf(Error)
expect(await run(notSpecialCharacters(), '财开云')).toBeUndefined()
})
})
describe('hooks/useMessage', () => {
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<string, unknown>
})
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: '<b>加粗</b><img src="x" onerror="alert(1)"><script>alert(2)</script><a href="javascript:alert(3)">链接</a>'
},
global: { plugins: [VueDOMPurifyHTML] }
})
const html = wrapper.find('.box').html()
expect(html).toContain('<b>加粗</b>')
expect(html).not.toContain('onerror')
expect(html).not.toContain('<script')
expect(html).not.toContain('javascript:')
})
})
+55
View File
@@ -0,0 +1,55 @@
import { setActivePinia } from 'pinia'
import { config } from '@vue/test-utils'
import { store } from '@/store'
// 业务模块在顶层调用 useXxxStore(),需在导入前激活全局 pinia(与 main.ts 中 setupStore 一致)
setActivePinia(store)
// jsdom 未实现 Web Locks;生产要求 HTTPS + navigator.locks,这里提供同名串行实现
if (!('locks' in navigator)) {
const queue = new Map<string, Promise<unknown>>()
Object.defineProperty(navigator, 'locks', {
configurable: true,
value: {
request: (name: string, callback: () => unknown) => {
const previous = queue.get(name) ?? Promise.resolve()
const next = previous.then(() => callback())
queue.set(
name,
next.catch(() => undefined)
)
return next
}
}
})
}
// element-plus 部分组件依赖 matchMedia / ResizeObserver
if (!window.matchMedia) {
window.matchMedia = (query: string) =>
({
matches: false,
media: query,
onchange: null,
addListener: () => undefined,
removeListener: () => undefined,
addEventListener: () => undefined,
removeEventListener: () => undefined,
dispatchEvent: () => false
}) as MediaQueryList
}
if (!('ResizeObserver' in window)) {
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
Object.defineProperty(window, 'ResizeObserver', { value: ResizeObserverStub })
}
config.global.stubs = { transition: false }
afterEach(() => {
localStorage.clear()
sessionStorage.clear()
})
+218
View File
@@ -0,0 +1,218 @@
import { createPinia, setActivePinia } from 'pinia'
import type { RouteLocationNormalizedLoaded } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { useDictStore } from '@/store/modules/dict'
import { usePermissionStore } from '@/store/modules/permission'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { getAuthSession, setToken, withAuthSessionLock } from '@/utils/auth'
import * as LoginApi from '@/api/login'
import * as DictDataApi from '@/api/system/dict/dict.data'
vi.mock('@/api/login', () => ({
getInfo: vi.fn(),
loginOut: vi.fn().mockResolvedValue(undefined)
}))
vi.mock('@/api/system/dict/dict.data', () => ({
getSimpleDictDataList: vi.fn()
}))
const { wsCache } = useCache()
// 字典缓存在 sessionStorage
const { wsCache: sessionCache } = useCache('sessionStorage')
const login = () =>
withAuthSessionLock(() =>
setToken(
{
id: 1,
accessToken: 'a',
refreshToken: 'r',
userId: 1,
userType: 2,
clientId: 'c',
expiresTime: 0
},
's1'
)
)
beforeEach(() => {
setActivePinia(createPinia())
})
describe('store/user', () => {
it('无令牌时重置状态且不请求用户信息', async () => {
const store = useUserStore()
await expect(store.setUserInfoAction()).resolves.toBeNull()
expect(LoginApi.getInfo).not.toHaveBeenCalled()
expect(store.getIsSetUser).toBe(false)
})
it('登录后加载权限、角色、用户并写入缓存', async () => {
await login()
vi.mocked(LoginApi.getInfo).mockResolvedValue({
permissions: ['system:user:query', 'system:user:update'],
roles: ['APP_ADMIN'],
user: { id: 9, avatar: '', nickname: '张三', deptId: 3 },
menus: [{ id: 1, path: '/system' }]
} as never)
const store = useUserStore()
await store.setUserInfoAction()
expect(store.getPermissions.has('system:user:update')).toBe(true)
expect(store.getRoles).toEqual(['APP_ADMIN'])
expect(store.getUser.nickname).toBe('张三')
expect(store.getIsSetUser).toBe(true)
expect(wsCache.get(CACHE_KEY.ROLE_ROUTERS)).toEqual([{ id: 1, path: '/system' }])
await store.setUserNicknameAction('李四')
await store.setUserAvatarAction('/a.png')
expect(wsCache.get(CACHE_KEY.USER).user).toMatchObject({ nickname: '李四', avatar: '/a.png' })
})
it('强制改密标记可清除', async () => {
await login()
vi.mocked(LoginApi.getInfo).mockResolvedValue({
permissions: [],
roles: [],
user: { id: 1, avatar: '', nickname: 'a', deptId: 1, forcePasswordChange: true },
menus: []
} as never)
const store = useUserStore()
await store.setUserInfoAction()
expect(store.getForcePasswordChange).toBe(true)
await store.clearForcePasswordChange()
expect(store.getForcePasswordChange).toBe(false)
expect(wsCache.get(CACHE_KEY.USER).user.forcePasswordChange).toBe(false)
})
it('退出登录清除令牌、用户缓存与旧版记住的口令', async () => {
await login()
wsCache.set(CACHE_KEY.USER, { user: { id: 1 } })
wsCache.set(CACHE_KEY.LoginForm, { username: 'u', password: 'p' })
const store = useUserStore()
store.permissions = new Set(['x'])
await store.loginOut()
expect(LoginApi.loginOut).toHaveBeenCalled()
expect(getAuthSession().accessToken).toBe('')
expect(wsCache.get(CACHE_KEY.USER)).toBeNull()
expect(wsCache.get(CACHE_KEY.LoginForm)).toBeNull()
expect(store.getPermissions.size).toBe(0)
})
})
describe('store/dict', () => {
const dictData = [
{ dictType: 'common_status', value: '0', label: '开启', colorType: 'primary', cssClass: '' },
{ dictType: 'common_status', value: '1', label: '关闭', colorType: 'info', cssClass: '' },
{ dictType: 'system_user_sex', value: '1', label: '男', colorType: '', cssClass: '' }
]
it('首次加载按 dictType 分组并缓存', async () => {
vi.mocked(DictDataApi.getSimpleDictDataList).mockResolvedValue(dictData as never)
const store = useDictStore()
await store.setDictMap()
expect(store.getIsSetDict).toBe(true)
expect(store.getDictByType('common_status')).toHaveLength(2)
expect(store.getDictByType('system_user_sex')[0]).toMatchObject({ value: '1', label: '男' })
expect(sessionCache.get(CACHE_KEY.DICT_CACHE)).toBeTruthy()
})
it('缓存命中时不再请求接口', async () => {
sessionCache.set(CACHE_KEY.DICT_CACHE, { cached_type: [{ value: 'x', label: 'X' }] })
const store = useDictStore()
await store.setDictMap()
expect(DictDataApi.getSimpleDictDataList).not.toHaveBeenCalled()
expect(store.getDictByType('cached_type')[0].label).toBe('X')
})
it('resetDict 强制重新拉取', async () => {
sessionCache.set(CACHE_KEY.DICT_CACHE, { old: [] })
vi.mocked(DictDataApi.getSimpleDictDataList).mockResolvedValue(dictData as never)
const store = useDictStore()
await store.resetDict()
expect(DictDataApi.getSimpleDictDataList).toHaveBeenCalledOnce()
expect(store.getDictByType('old')).toBeUndefined()
expect(store.getDictByType('common_status')).toHaveLength(2)
})
})
describe('store/permission', () => {
it('根据缓存菜单生成动态路由并在末尾追加 404', async () => {
wsCache.set(CACHE_KEY.ROLE_ROUTERS, [
{
id: 1,
parentId: 0,
name: '系统管理',
path: '/system',
icon: 'ep:setting',
visible: true,
keepAlive: true,
children: [
{
id: 2,
parentId: 1,
name: '用户管理',
path: 'user',
component: 'system/user/user/index',
componentName: 'SystemUser',
visible: true,
keepAlive: true
}
]
}
])
const store = usePermissionStore()
await store.generateRoutes()
const added = store.addRouters
expect(added[0]).toMatchObject({ path: '/system', meta: { title: '系统管理', alwaysShow: true } })
expect(typeof added[0].component).toBe('function')
expect(added[0].children![0]).toMatchObject({ name: 'SystemUser', meta: { title: '用户管理' } })
expect(added[added.length - 1].name).toBe('404Page')
expect(store.getRouters.some((r) => r.path === '/system')).toBe(true)
store.setMenuTabRouters(added)
expect(store.getMenuTabRouters).toBe(added)
})
})
describe('store/tagsView', () => {
const view = (path: string, extra: Partial<RouteLocationNormalizedLoaded> = {}) =>
({
path,
fullPath: path,
name: path.replace(/\W/g, '') || 'root',
meta: { title: path },
matched: [],
...extra
}) as unknown as RouteLocationNormalizedLoaded
it('新增标签去重、同名标题加序号并维护缓存', () => {
const store = useTagsViewStore()
store.addView(view('/a'))
store.addView(view('/a'))
store.addView(view('/a', { fullPath: '/a?id=2' }))
store.addView(view('/b', { meta: { title: '/b', noCache: true } } as never))
store.addView(view('/hidden', { meta: { title: 'h', noTagsView: true } } as never))
expect(store.getVisitedViews.map((v) => v.fullPath)).toEqual(['/a', '/a?id=2', '/b'])
expect(store.getVisitedViews[1].meta.titleSuffix).toBe('2')
expect([...store.getCachedViews]).toEqual(['a'])
})
it('关闭左侧、右侧、其他与修改标题', () => {
const store = useTagsViewStore()
;['/1', '/2', '/3', '/4'].forEach((p) => store.addView(view(p)))
store.delLeftViews(view('/2'))
expect(store.getVisitedViews.map((v) => v.path)).toEqual(['/2', '/3', '/4'])
store.delRightViews(view('/3'))
expect(store.getVisitedViews.map((v) => v.path)).toEqual(['/2', '/3'])
store.delOthersViews(view('/3'))
expect(store.getVisitedViews.map((v) => v.path)).toEqual(['/3'])
store.setSelectedTag(view('/3'))
store.setTitle('新标题')
expect(store.getVisitedViews[0].meta.title).toBe('新标题')
store.updateVisitedView(view('/3', { query: { x: '1' } } as never))
expect(store.getVisitedViews[0].query).toEqual({ x: '1' })
store.delView(view('/3'))
expect(store.getVisitedViews).toHaveLength(0)
})
})
+153
View File
@@ -0,0 +1,153 @@
import {
AUTH_SESSION_KEY,
assertAuthSessionLockHeld,
createAuthNonce,
formatToken,
getAccessToken,
getAuthSession,
getRefreshToken,
getTenantId,
getVisitTenantId,
isAuthSessionCurrent,
isPageSessionCurrent,
removeToken,
setTenantId,
setToken,
setVisitTenantId,
withAuthSessionLock
} from '@/utils/auth'
import {
appUrl,
assertSsoFlowCurrent,
beginSsoFlow,
completeSsoFlow,
consumeSsoFlow,
currentAppPath,
isIdentityCenterPage,
safeRedirect
} from '@/utils/ssoFlow'
import type { TokenType } from '@/api/login/types'
const token = (access: string, refresh: string, binding?: string): TokenType => ({
id: 1,
accessToken: access,
refreshToken: refresh,
userId: 1,
userType: 2,
clientId: 'ckcloud',
expiresTime: 0,
ssoSessionBinding: binding
})
describe('utils/auth 登录会话', () => {
it('无会话或存储损坏时返回空会话', () => {
expect(getAuthSession()).toEqual({
accessToken: '',
refreshToken: '',
sessionId: '',
ssoSessionBinding: ''
})
localStorage.setItem(AUTH_SESSION_KEY, '{broken')
expect(getAccessToken()).toBe('')
localStorage.setItem(AUTH_SESSION_KEY, JSON.stringify({ accessToken: 1 }))
expect(getRefreshToken()).toBe('')
})
it('令牌只能在跨标签页锁内写入', () => {
expect(() => setToken(token('a', 'r'))).toThrow('登录状态必须在跨标签页锁内更新')
expect(() => assertAuthSessionLockHeld()).toThrow()
})
it('锁内一次写入完整令牌对,同会话续期保留 SSO 绑定', async () => {
await withAuthSessionLock(() => setToken(token('a1', 'r1', 'bind-1'), 'sid'))
expect(getAuthSession()).toEqual({
accessToken: 'a1',
refreshToken: 'r1',
sessionId: 'sid',
ssoSessionBinding: 'bind-1'
})
expect(isPageSessionCurrent()).toBe(true)
await withAuthSessionLock(() => setToken(token('a2', 'r1'), 'sid'))
expect(getAuthSession().ssoSessionBinding).toBe('bind-1')
const snapshot = getAuthSession()
expect(isAuthSessionCurrent(snapshot)).toBe(true)
await withAuthSessionLock(() => setToken(token('a3', 'r1'), 'sid'))
expect(isAuthSessionCurrent(snapshot)).toBe(false)
})
it('不完整的登录响应被拒绝', async () => {
await expect(withAuthSessionLock(() => setToken(token('', 'r')))).rejects.toThrow(
'登录响应不完整'
)
})
it('removeToken 清除会话', async () => {
await withAuthSessionLock(() => setToken(token('a', 'r'), 'sid'))
await withAuthSessionLock(() => removeToken())
expect(getAccessToken()).toBe('')
})
it('锁按顺序串行执行', async () => {
const order: number[] = []
await Promise.all([
withAuthSessionLock(async () => {
await new Promise((r) => setTimeout(r, 10))
order.push(1)
}),
withAuthSessionLock(() => {
order.push(2)
})
])
expect(order).toEqual([1, 2])
})
it('随机数、令牌格式与租户缓存', () => {
expect(createAuthNonce()).toMatch(/^[0-9a-f]{64}$/)
expect(formatToken('x')).toBe('Bearer x')
setTenantId(1)
setVisitTenantId(2)
expect(getTenantId()).toBe(1)
expect(getVisitTenantId()).toBe(2)
})
})
describe('utils/ssoFlow 单点登录流程', () => {
it('appUrl / currentAppPath / isIdentityCenterPage', () => {
expect(appUrl('/sso/login')).toBe(`${location.origin}/sso/login`)
expect(currentAppPath()).toBe(location.pathname + location.search + location.hash)
expect(isIdentityCenterPage()).toBe(false)
})
it('safeRedirect 只允许站内业务路径,拦截外链与登录页', () => {
expect(safeRedirect('/system/user?id=1#x')).toBe('/system/user?id=1#x')
expect(safeRedirect('//evil.com/a')).toBe('/')
expect(safeRedirect('https://evil.com')).toBe('/')
expect(safeRedirect('/a\\b')).toBe('/')
expect(safeRedirect('/sso/callback')).toBe('/')
expect(safeRedirect('/zcy/login')).toBe('/')
expect(safeRedirect('/auth-status')).toBe('/')
expect(safeRedirect('/403')).toBe('/')
expect(safeRedirect(123)).toBe('/')
})
it('发起的流程只能被同一 requestId 与类型消费一次', async () => {
const flow = await beginSsoFlow('login', '/system/user', 'org-1')
expect(flow.redirect).toBe('/system/user')
expect(flow.organizationKey).toBe('org-1')
expect(() => consumeSsoFlow('other', 'login')).toThrow('登录请求不匹配')
expect(() => consumeSsoFlow(flow.requestId, 'logout')).toThrow('登录请求不匹配')
const consumed = consumeSsoFlow(flow.requestId, 'login')
expect(consumed.requestId).toBe(flow.requestId)
expect(() => consumeSsoFlow(flow.requestId, 'login')).toThrow('登录请求已失效')
})
it('新流程覆盖旧流程,过期流程失效', async () => {
const first = await beginSsoFlow('login')
await beginSsoFlow('logout')
expect(() => assertSsoFlowCurrent(first)).toThrow('登录状态已变更')
const second = await beginSsoFlow('login')
expect(() => assertSsoFlowCurrent({ ...second, createdAt: Date.now() - 9 * 3600_000 })).toThrow()
await withAuthSessionLock(() => completeSsoFlow(second))
expect(() => assertSsoFlowCurrent(second)).toThrow()
})
})
+36
View File
@@ -0,0 +1,36 @@
import { colorIsDark, getCssColorVariable, hexToRGB, isHexColor, lighten, mix } from '@/utils/color'
describe('utils/color', () => {
it('isHexColor 只接受 3/6 位十六进制', () => {
expect(isHexColor('#fff')).toBe(true)
expect(isHexColor('#B7390B')).toBe(true)
expect(isHexColor('fff')).toBe(false)
expect(isHexColor('#ffff')).toBe(false)
})
it('hexToRGB 支持简写与透明度,非法值原样返回小写', () => {
expect(hexToRGB('#fff')).toBe('RGB(255,255,255)')
expect(hexToRGB('#000000', 0.5)).toBe('RGBA(0,0,0,0.5)')
expect(hexToRGB('RED')).toBe('red')
})
it('colorIsDark 按亮度判断', () => {
expect(colorIsDark('#000000')).toBe(true)
expect(colorIsDark('#ffffff')).toBe(false)
expect(colorIsDark('nope')).toBeUndefined()
})
it('lighten 与 mix 计算结果', () => {
expect(lighten('#000000', 100)).toBe('#ffffff')
expect(lighten('101010', 0)).toBe('#101010')
expect(mix('#ffffff', '#000000', 0.5)).toBe('#808080')
expect(mix('#ff0000', '#0000ff', 1)).toBe('#ff0000')
})
it('getCssColorVariable 读取根节点变量', () => {
document.documentElement.style.setProperty('--el-color-primary', '#409eff')
expect(getCssColorVariable()).toBe('#409eff')
expect(getCssColorVariable('--el-color-primary', 0.2)).toBe('RGBA(64,158,255,0.2)')
expect(getCssColorVariable('--not-exist')).toBe('')
})
})
+87
View File
@@ -0,0 +1,87 @@
import {
fileSizeFormatter,
findIndex,
formatTime,
generateUUID,
getUrlValue,
humpToUnderline,
jsonParse,
setCssVar,
subString,
trim
} from '@/utils'
import { dateFormatter, formatDate, formatPast2 } from '@/utils/formatTime'
describe('utils/index', () => {
it('字符串工具', () => {
expect(humpToUnderline('leftMenuWidth')).toBe('left-menu-width')
expect(trim(' a b ')).toBe('a b')
expect(subString('abcdef', 0, 3)).toBe('abc')
expect(subString('ab', 0, 3)).toBe('ab')
})
it('findIndex 返回首个命中下标', () => {
expect(findIndex([1, 2, 3], (v: number) => v > 1)).toBe(1)
expect(findIndex([1], (v: number) => v > 5)).toBe(-1)
})
it('formatTime 支持年月日时分秒', () => {
const date = new Date(2026, 9, 27, 8, 5, 9)
expect(formatTime(date, 'yyyy-MM-dd HH:mm:ss')).toBe('2026-10-27 08:05:09')
expect(formatTime(date.getTime(), 'yy/M/d')).toBe('26/10/27')
expect(formatTime('', 'yyyy')).toBe('')
})
it('generateUUID 生成 v4 格式', () => {
const id = generateUUID()
expect(id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/)
expect(generateUUID()).not.toBe(id)
})
it('fileSizeFormatter 以 1024 进位', () => {
expect(fileSizeFormatter(null, null, 1024)).toBe('1.00 KB')
expect(fileSizeFormatter(null, null, '1572864')).toBe('1.50 MB')
expect(fileSizeFormatter(null, null, 10)).toBe('10.00 Bytes')
})
it('getUrlValue 读取查询参数', () => {
expect(getUrlValue('id', 'https://a.com/x?id=12&b=2')).toBe('12')
expect(getUrlValue('none', 'https://a.com/x?id=12')).toBe('')
expect(getUrlValue('', 'https://a.com')).toBe('')
})
it('jsonParse 失败时原样返回', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
expect(jsonParse('{"a":1}')).toEqual({ a: 1 })
expect(jsonParse('not json')).toBe('not json')
expect(warn).toHaveBeenCalledOnce()
})
it('setCssVar 写入样式变量', () => {
const el = document.createElement('div')
setCssVar('--x', '10px', el)
expect(el.style.getPropertyValue('--x')).toBe('10px')
})
})
describe('utils/formatTime', () => {
it('formatDate 默认格式与自定义格式', () => {
const d = new Date(2026, 0, 2, 3, 4, 5)
expect(formatDate(d)).toBe('2026-01-02 03:04:05')
expect(formatDate(d, 'YYYY/MM/DD')).toBe('2026/01/02')
expect(formatDate(null)).toBe('')
})
it('formatPast2 把毫秒转成中文时长', () => {
expect(formatPast2(0)).toBe('0 秒')
expect(formatPast2(5_000)).toBe('5 秒')
expect(formatPast2(3 * 60_000)).toBe('3 分钟')
expect(formatPast2(2 * 3_600_000 + 60_000)).toBe('2 小时 1 分钟')
expect(formatPast2(26 * 3_600_000)).toBe('1 天2 小时 0 分钟')
})
it('dateFormatter 用于表格列', () => {
expect(dateFormatter({}, {}, new Date(2026, 9, 1))).toBe('2026-10-01 00:00:00')
expect(dateFormatter({}, {}, undefined)).toBe('')
})
})
+50
View File
@@ -0,0 +1,50 @@
import {
is,
isArray,
isBoolean,
isDef,
isEmpty,
isFunction,
isNull,
isNumber,
isObject,
isString,
isUnDef,
isUrl
} from '@/utils/is'
describe('utils/is', () => {
it('基础类型判断', () => {
expect(is(new Date(), 'Date')).toBe(true)
expect(isDef(0)).toBe(true)
expect(isUnDef(undefined)).toBe(true)
expect(isObject({})).toBe(true)
expect(isObject(null)).toBe(false)
expect(isObject([])).toBe(false)
expect(isNull(null)).toBe(true)
expect(isNumber(1)).toBe(true)
expect(isNumber('1')).toBe(false)
expect(isString('a')).toBe(true)
expect(isFunction(() => 1)).toBe(true)
expect(isBoolean(false)).toBe(true)
expect(isArray([1])).toBe(true)
})
it('isEmpty 覆盖空值、字符串、数组、Map/Set 与对象', () => {
expect(isEmpty(null)).toBe(true)
expect(isEmpty(undefined)).toBe(true)
expect(isEmpty('')).toBe(true)
expect(isEmpty([])).toBe(true)
expect(isEmpty(new Map())).toBe(true)
expect(isEmpty(new Set([1]))).toBe(false)
expect(isEmpty({})).toBe(true)
expect(isEmpty({ a: 1 })).toBe(false)
expect(isEmpty(0)).toBe(false)
})
it('isUrl 识别外链', () => {
expect(isUrl('https://cxtest.zjsck.com:8443/portal/')).toBe(true)
expect(isUrl('http://a.com/x?y=1#z')).toBe(true)
expect(isUrl('/system/user')).toBe(false)
})
})
+33
View File
@@ -0,0 +1,33 @@
import { parseParameterValue, validateParameterValue } from '@/utils/parameterValue'
describe('utils/parameterValue', () => {
it('number 类型拒绝空白、非数字与无穷大', () => {
expect(validateParameterValue('', 'number').valid).toBe(false)
expect(validateParameterValue(' ', 'number').valid).toBe(false)
expect(validateParameterValue('abc', 'number')).toEqual({
valid: false,
message: '请输入合法的有限数字'
})
expect(validateParameterValue('Infinity', 'number').valid).toBe(false)
expect(validateParameterValue('12.5', 'number')).toEqual({ valid: true })
})
it('boolean 类型只接受 true/false 字面量', () => {
expect(validateParameterValue('true', 'boolean').valid).toBe(true)
expect(validateParameterValue('false', 'boolean').valid).toBe(true)
expect(validateParameterValue('1', 'boolean').message).toBe('请选择「是」或「否」')
})
it('json 类型校验语法', () => {
expect(validateParameterValue('{"a":1}', 'json').valid).toBe(true)
expect(validateParameterValue('{a:1}', 'json').message).toBe('请输入合法的 JSON')
})
it('按声明类型解析,非法值抛出校验信息', () => {
expect(parseParameterValue('42', 'number')).toBe(42)
expect(parseParameterValue('false', 'boolean')).toBe(false)
expect(parseParameterValue('[1,2]', 'json')).toEqual([1, 2])
expect(parseParameterValue(' raw ', 'string')).toBe(' raw ')
expect(() => parseParameterValue('x', 'number')).toThrow('请输入合法的有限数字')
})
})
+89
View File
@@ -0,0 +1,89 @@
import { defineComponent, h, withDirectives, resolveDirective, createApp } from 'vue'
import { mount } from '@vue/test-utils'
import { MenuPermission } from '@/utils/menuPermission'
import { checkPermi, checkRole } from '@/utils/permission'
import { hasPermission } from '@/directives/permission/hasPermi'
import { setupAuth, setupMountedFocus } from '@/directives'
import { useUserStore } from '@/store/modules/user'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const grant = (...permissions: string[]) => {
useUserStore().permissions = new Set(permissions)
}
describe('utils/permission 与 v-hasPermi / v-hasRole', () => {
it('checkPermi 命中任一权限或全部权限通配', () => {
grant('system:user:query')
expect(checkPermi(['system:user:query', 'x'])).toBe(true)
expect(checkPermi(['system:user:delete'])).toBe(false)
grant('*:*:*')
expect(hasPermission(['anything'])).toBe(true)
})
it('checkRole 读取缓存用户角色,超管放行,空参数返回 false', () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined)
wsCache.set(CACHE_KEY.USER, { roles: ['APP_ADMIN'] })
expect(checkRole(['APP_ADMIN'])).toBe(true)
expect(checkRole(['OTHER'])).toBe(false)
wsCache.set(CACHE_KEY.USER, { roles: ['super_admin'] })
expect(checkRole(['OTHER'])).toBe(true)
expect(checkRole([])).toBe(false)
expect(error).toHaveBeenCalled()
})
const Buttons = defineComponent({
setup() {
const hasPermi = resolveDirective('hasPermi')!
const hasRole = resolveDirective('hasRole')!
return () =>
h('div', [
withDirectives(h('button', { id: 'del' }, '删除'), [[hasPermi, ['system:user:delete']]]),
withDirectives(h('button', { id: 'query' }, '查询'), [[hasPermi, ['system:user:query']]]),
withDirectives(h('button', { id: 'admin' }, '管理'), [[hasRole, ['APP_ADMIN']]])
])
}
})
it('无权限的按钮被移除,有权限的保留', () => {
grant('system:user:query')
wsCache.set(CACHE_KEY.USER, { roles: ['VIEWER'] })
const wrapper = mount(Buttons, { global: { plugins: [{ install: setupAuth }] } })
expect(wrapper.find('#query').exists()).toBe(true)
expect(wrapper.find('#del').exists()).toBe(false)
expect(wrapper.find('#admin').exists()).toBe(false)
})
it('角色匹配时保留按钮', () => {
grant()
wsCache.set(CACHE_KEY.USER, { roles: ['APP_ADMIN'] })
const wrapper = mount(Buttons, { global: { plugins: [{ install: setupAuth }] } })
expect(wrapper.find('#admin').exists()).toBe(true)
})
it('指令值为空时抛错,提示使用方式', () => {
const app = createApp({ render: () => null })
setupAuth(app)
const directive = app.directive('hasPermi') as (
el: Element,
binding: { value: unknown }
) => void
expect(() => directive(document.createElement('i'), { value: [] })).toThrow()
})
it('v-mountedFocus 挂载后聚焦', () => {
const Input = defineComponent({
setup() {
const focus = resolveDirective('mountedFocus')!
return () => withDirectives(h('input', { id: 'i' }), [[focus]])
}
})
const wrapper = mount(Input, {
attachTo: document.body,
global: { plugins: [{ install: setupMountedFocus }] }
})
expect(document.activeElement?.id).toBe('i')
wrapper.unmount()
})
})
+101
View File
@@ -0,0 +1,101 @@
import {
eachTree,
filter,
findNode,
findPath,
forEach,
handleTree,
handleTree2,
treeMap,
treeToList
} from '@/utils/tree'
interface Dept {
id: number
parentId: number
name: string
children?: Dept[]
}
const flat = (): Dept[] => [
{ id: 1, parentId: 0, name: '财开' },
{ id: 2, parentId: 1, name: '信息部' },
{ id: 3, parentId: 1, name: '财务部' },
{ id: 4, parentId: 2, name: '开发组' },
{ id: 5, parentId: 99, name: '孤立节点' }
]
describe('utils/tree', () => {
it('handleTree 按 parentId 组装树,父节点不存在的作为根', () => {
const tree = handleTree<Dept>(flat())
expect(tree.map((n) => n.id)).toEqual([1, 5])
expect(tree[0].children!.map((n) => n.id)).toEqual([2, 3])
expect(tree[0].children![0].children![0].name).toBe('开发组')
})
it('handleTree 非数组输入返回空数组', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
expect(handleTree(null as unknown as Dept[])).toEqual([])
expect(warn).toHaveBeenCalled()
})
it('handleTree 支持自定义字段名', () => {
const data = [
{ key: 'a', pid: '', label: 'A' },
{ key: 'b', pid: 'a', label: 'B' }
]
const tree = handleTree<Record<string, unknown>>(data, 'key', 'pid', 'items')
expect(tree).toHaveLength(1)
expect((tree[0].items as unknown[]).length).toBe(1)
})
it('handleTree2 以 rootId 取根且不修改入参', () => {
const files = [
{ id: 'src', parentId: '/', label: 'src' },
{ id: 'src/a.ts', parentId: 'src', label: 'a.ts' }
]
const tree = handleTree2(files, 'id', 'parentId', 'children', '/')
expect(tree).toHaveLength(1)
expect((tree[0] as { children?: unknown[] }).children).toHaveLength(1)
expect('children' in files[0]).toBe(false)
// 默认根取最小 parentId
const numeric = handleTree2(flat().slice(0, 4))
expect(numeric.map((n) => n.id)).toEqual([1])
})
it('treeToList / findNode / findPath / forEach 遍历', () => {
const tree = handleTree<Dept>(flat())
expect(treeToList(tree).map((n) => n.id)).toEqual([1, 2, 4, 3, 5])
expect(findNode(tree, (n) => n.id === 4)?.name).toBe('开发组')
expect(findNode(tree, (n) => n.id === 404)).toBeNull()
expect(findPath(tree, (n) => n.id === 4)?.map((n) => n.id)).toEqual([1, 2, 4])
expect(findPath(tree, (n) => n.id === 404)).toBeNull()
const visited: number[] = []
forEach(tree, (n) => {
visited.push(n.id)
return n.id === 2 // 返回 true 终止遍历
})
expect(visited).toEqual([1, 2])
})
it('filter 保留命中节点及其祖先', () => {
const tree = handleTree<Dept>(flat())
const result = filter(tree, (n) => n.name === '开发组')
expect(result.map((n) => n.id)).toEqual([1])
expect(result[0].children!.map((n) => n.id)).toEqual([2])
expect(result[0].children![0].children!.map((n) => n.id)).toEqual([4])
})
it('treeMap 转换结构,eachTree 传入父节点', () => {
const tree = handleTree<Dept>(flat())
const mapped = treeMap(tree, { conversion: (n: Dept) => ({ value: n.id, label: n.name }) })
expect(mapped[0]).toMatchObject({ value: 1, label: '财开' })
expect((mapped[0] as unknown as { children: unknown[] }).children).toHaveLength(2)
const parents: Record<number, string | undefined> = {}
eachTree(tree, (node: Dept, parent: Dept) => {
parents[node.id] = parent.name
})
expect(parents[4]).toBe('信息部')
expect(parents[1]).toBeUndefined()
})
})
+67
View File
@@ -0,0 +1,67 @@
import { flushPromises, mount, shallowMount } from '@vue/test-utils'
import type { Component } from 'vue'
import { appPlugins, loginAsAdmin, mockBackend } from '../helpers/app'
/**
* 页面冒烟测试:逐个挂载 src/views 下的页面与页面组件(子组件浅渲染),
* 走真实的 request 封装(网络层替换为空数据),断言能渲染出 DOM 且不抛异常。
* 用于发现导入错误、setup 运行时异常、模板引用了不存在的变量等回归。
*/
const pages = import.meta.glob<{ default: Component }>('/src/views/**/*.vue')
interface SmokeOptions {
/** 必填 props 的最小合法值 */
props?: Record<string, unknown>
/** 父组件通过 provide 注入的数据 */
provide?: Record<string, unknown>
/** 通过 ref 调用子组件方法的页面需完整渲染子组件 */
deep?: boolean
/** 无法在 jsdom 中渲染的页面,写明原因 */
skip?: string
}
const options: Record<string, SmokeOptions> = {
'/src/views/Home/Index2.vue': { skip: 'echarts-wordcloud 依赖 canvas,jsdom 不支持' },
'/src/views/Redirect/Redirect.vue': { skip: '依赖路由 params.path,由路由守卫在浏览器中验证' },
'/src/views/Profile/components/BasicInfo.vue': { deep: true }
}
const entries = Object.keys(pages)
.sort()
.filter((path) => !options[path]?.skip)
describe('views 冒烟渲染', () => {
it('跳过的页面都写明了原因', () => {
for (const [path, option] of Object.entries(options)) {
expect(Object.keys(pages)).toContain(path)
if (option.skip !== undefined) expect(option.skip.length).toBeGreaterThan(5)
}
})
beforeEach(async () => {
await loginAsAdmin()
})
it.each(entries)('%s', async (path) => {
mockBackend()
const errors: unknown[] = []
const mod = await pages[path]()
const option = options[path] ?? {}
const wrapper = (option.deep ? mount : shallowMount)(mod.default, {
props: option.props,
global: {
plugins: appPlugins(),
provide: option.provide,
config: {
errorHandler: (err) => {
errors.push(err)
}
}
}
})
await flushPromises()
expect(errors).toEqual([])
expect(wrapper.html().length).toBeGreaterThan(0)
wrapper.unmount()
})
})