以 ckcloudManage a44810c 为基础,只保留资产页面(台账、单据、基础数据、同步任务)、 登录/错误/个人资料等公共页面,以及资产单据“查看流程”用到的流程详情页; 统一登录应用编码默认 CK_ASSET,标题“资产管理”,本地端口 9090。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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('')
|
||||
})
|
||||
})
|
||||
@@ -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('')
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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('请输入合法的有限数字')
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user