city_vocational_college/tests/route-integration.test.js

164 lines
9.3 KiB
JavaScript
Raw Permalink 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.

import test from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync, readdirSync } from 'node:fs'
import vm from 'node:vm'
import { filterRetainedRoutes, findFirstMenuRoute, isRemovedPath, normalizeViewPath } from '../src/utils/navigation.js'
/**
* 用真实本地页面清单执行 store,使菜单注册测试能发现缺失页面及路径解析错误。
* 仅替代 HTTP 和 Vue 注入边界,组件可用性、菜单筛选与导航选择仍运行真实实现。
* @param {Array} data 模拟后端按当前账号授权返回的菜单树。
* @param {Error} [failure] 路由接口需要抛出的错误,用于验证失败传播。
* @returns {Object} 可执行 generateRoutes 并检查导航状态的 permission store。
*/
function loadPermissionStore(data, failure) {
const modules = Object.fromEntries(readdirSync(new URL('../src/views/', import.meta.url), { recursive: true })
.filter(file => file.endsWith('.vue'))
.map(file => [`./../../views/${file.replaceAll('\\', '/')}`, async () => ({})]))
const source = readFileSync(new URL('../src/store/modules/permission.js', import.meta.url), 'utf8')
.replace(/^import .+\r?\n/gm, '')
.replace("import.meta.glob('./../../views/**/*.vue')", 'sourceModules')
.replace('export default usePermissionStore', 'globalThis.factory = usePermissionStore')
.replace(/export /g, '')
const context = {
sourceModules: modules, settings: { hideMenuManagement: true }, filterRetainedRoutes, findFirstMenuRoute, normalizeViewPath,
constantRoutes: [], dynamicRoutes: [], Layout: {}, ParentView: {}, InnerLink: {}, auth: {},
router: { addRoute() {} }, console: { ...console, error() {} },
getRouters: async () => { if (failure) throw failure; return { data } },
defineStore: (name, options) => () => ({ ...options.state(), ...options.actions })
}
vm.runInNewContext(source, context)
return context.factory()
}
/** 捕获实际守卫,测试首次动态注册和后续导航,不启动浏览器或真实认证请求。 */
function loadGuard({ roles = [], homeRoute = { path: '/system/user' }, token = 'token', locked = false } = {}) {
let guard
const added = []
const user = { roles, getInfo: async () => { user.roles = ['user'] }, logOut: async () => { user.roles = [] } }
const permission = { homeRoute, generateRoutes: async () => [{ path: '/system' }] }
const source = readFileSync(new URL('../src/permission.js', import.meta.url), 'utf8').replace(/^import .+\r?\n/gm, '')
const context = {
router: { beforeEach(callback) { guard = callback }, afterEach() {}, addRoute(route) { added.push(route.path) } },
NProgress: { configure() {}, start() {}, done() {} }, ElMessage: { error() {} }, isRelogin: {}, isRemovedPath,
getToken: () => token, isHttp: path => /^https?:/.test(path), isPathMatch: (pattern, path) => pattern === path,
useUserStore: () => user, usePermissionStore: () => permission,
useLockStore: () => ({ isLock: locked }), useSettingsStore: () => ({ setTitle() {} })
}
vm.runInNewContext(source, context)
return { guard, added }
}
test('真实store从授权树移除旧模块且忽略本地不存在的组件,默认进入首个有效菜单', async () => {
const store = loadPermissionStore([
{ path: '/vi', component: 'Layout', meta: { title: '语音交互' }, children: [{ path: 'project', component: 'vi/project/index' }] },
{ path: '/broken', component: 'Layout', meta: { title: '旧目录' }, children: [{ path: 'missing', component: 'missing/view' }] },
{ path: '/system', component: 'Layout', meta: { title: '系统管理' }, children: [
{ path: 'menu', component: 'system/menu/index', meta: { title: '菜单管理' } },
{ path: 'section', component: 'ParentView', children: [{ path: 'user', component: 'system/user/index', meta: { title: '用户管理' } }] }
] }
])
const registered = await store.generateRoutes()
assert.deepEqual(Array.from(registered, route => route.path), ['/system'])
assert.equal(registered[0].children[0].hidden, true)
assert.equal(registered[0].children[1].path, 'section/user')
assert.equal(store.homeRoute.path, '/system/section/user')
for (const tree of [store.routes, store.sidebarRouters, store.topbarRouters, store.defaultRoutes]) {
assert.deepEqual(Array.from(tree, route => route.path), ['/system'])
}
})
test('真实store注册移植后的全部资源和测试页面,侧栏保留授权与源项目隐藏策略', async () => {
const resourceViews = ['robot', 'device', 'map', 'terminal', 'visionCalibration']
const testViews = ['configs', 'detect', 'params', 'log', 'history']
const data = [
{ path: '/resource', component: 'Layout', meta: { title: '资源中心' }, children: resourceViews.map(view => ({
path: view, component: `resource/${view}/index`, meta: { title: view }, permissions: [`resource:${view}:list`]
})) },
{ path: '/test', component: 'Layout', meta: { title: '测试管理' }, children: testViews.map(view => ({
path: view, component: `test/${view}/index`, meta: { title: view }, permissions: [`test:${view}:list`]
})) }
]
const original = structuredClone(data)
const store = loadPermissionStore(data)
const registered = await store.generateRoutes()
assert.deepEqual(Array.from(registered, route => route.path), ['/resource', '/test'])
assert.deepEqual(Array.from(registered[0].children, route => route.path), resourceViews)
assert.deepEqual(Array.from(registered[1].children, route => route.path), testViews)
assert.equal(store.homeRoute.path, '/resource/robot')
assert.equal(typeof registered[0].children[0].component, 'function')
assert.equal(typeof registered[1].children[0].component, 'function')
for (const tree of [store.sidebarRouters, store.topbarRouters, store.defaultRoutes]) {
assert.deepEqual(Array.from(tree, route => route.path), ['/resource', '/test'])
assert.equal(tree[0].children[3].hidden, true)
assert.equal(tree[0].children[4].hidden, true)
assert.deepEqual(Array.from(tree[1].children[0].permissions), ['test:configs:list'])
}
assert.deepEqual(data, original)
const onlyTest = loadPermissionStore([data[1]])
await onlyTest.generateRoutes()
assert.equal(onlyTest.homeRoute.path, '/test/configs')
})
test('已登录可直接访问资源和测试授权链接,未登录仍先进入登录页', async () => {
const { guard } = loadGuard({ roles: ['user'] })
for (const path of ['/resource/robot', '/test/configs']) {
assert.equal(await guard({ path, fullPath: path, meta: {} }), true)
const guest = loadGuard({ token: '' })
assert.equal(await guest.guard({ path, fullPath: path, meta: {} }), `/login?redirect=${path}`)
}
})
test('真实store兼容源项目菜单组件前缀、扩展名及Windows分隔符', async () => {
const components = [
'@/views/resource/robot/index.vue', 'src/views/resource/robot/index.vue',
'views/resource/robot/index.vue', '/resource/robot/index.vue',
' resource\\robot\\index.vue '
]
const store = loadPermissionStore([{ path: '/resource', component: 'Layout', children: components.map((component, index) => ({
path: `robot-${index}`, component, meta: { title: '机器人' }
})) }])
const registered = await store.generateRoutes()
assert.equal(registered.length, 1)
assert.equal(registered[0].children.length, components.length)
for (const child of registered[0].children) assert.equal(typeof child.component, 'function')
})
test('真实store在无保留菜单时提供可退出的401,路由接口失败正常reject', async () => {
const store = loadPermissionStore([{ path: '/vi', component: 'Layout' }])
await store.generateRoutes()
assert.equal(store.homeRoute.path, '/401')
assert.equal(store.homeRoute.query.noGoBack, 'true')
await assert.rejects(loadPermissionStore([], new Error('offline')).generateRoutes(), /offline/)
})
test('首次根导航注册动态路由后进入首个授权菜单', async () => {
const { guard, added } = loadGuard()
const target = await guard({ path: '/', fullPath: '/', meta: {} })
assert.equal(target.path, '/system/user')
assert.equal(target.replace, true)
assert.deepEqual(added, ['/system'])
})
test('已登录访问旧业务书签时转入保留菜单,直接页面链接保留query/hash并重新解析', async () => {
const { guard } = loadGuard({ roles: ['user'] })
assert.equal((await guard({ path: '/vi/plan/index/1', meta: {} })).path, '/system/user')
const first = loadGuard()
const target = await first.guard({ path: '/system/user', name: 'NotFound', query: { page: '2' }, hash: '#list', meta: {} })
assert.equal(target.path, '/system/user')
assert.equal(target.query.page, '2')
assert.equal(target.hash, '#list')
assert.equal(target.name, undefined)
})
test('没有菜单的401允许显示,未登录和锁屏仍沿用原认证边界', async () => {
const noMenus = loadGuard({ homeRoute: { path: '/401', query: { noGoBack: 'true' } } })
assert.equal((await noMenus.guard({ path: '/', meta: {} })).path, '/401')
const ready = loadGuard({ roles: ['user'], homeRoute: { path: '/401' } })
assert.equal(await ready.guard({ path: '/401', meta: {} }), true)
const guest = loadGuard({ token: '' })
assert.equal(await guest.guard({ path: '/', fullPath: '/', meta: {} }), '/login?redirect=/')
const locked = loadGuard({ roles: ['user'], locked: true })
assert.equal((await locked.guard({ path: '/', meta: {} })).path, '/lock')
})