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