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() }) })