usePermission.test.js 2.38 KB
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { usePermission } from './usePermission'
import { getActionPermissionConfig } from '@/config/permissions'

const show_modal_mock = vi.fn()
const navigate_to_mock = vi.fn()
const get_current_pages_mock = vi.fn()
const add_mock = vi.fn()
let user_state = { isLoggedIn: false }

vi.mock('@tarojs/taro', () => ({
    default: {
        showModal: (...args) => show_modal_mock(...args),
        navigateTo: (...args) => navigate_to_mock(...args),
        getCurrentPages: () => get_current_pages_mock()
    }
}))

vi.mock('@/stores/user', () => ({
    useUserStore: () => user_state
}))

vi.mock('@/stores/router', () => ({
    routerStore: () => ({
        add: add_mock
    })
}))

describe('usePermission', () => {
    beforeEach(() => {
        show_modal_mock.mockReset()
        navigate_to_mock.mockReset()
        get_current_pages_mock.mockReset()
        add_mock.mockReset()
        user_state = { isLoggedIn: false }
    })

    it('requireAction 登录状态下执行回调', () => {
        user_state.isLoggedIn = true
        const callback = vi.fn()
        const { requireAction } = usePermission()
        const result = requireAction('view_material', callback)
        expect(result).toBe(true)
        expect(callback).toHaveBeenCalledTimes(1)
        expect(show_modal_mock).not.toHaveBeenCalled()
    })

    it('requireAction 未登录时保存回跳并跳转登录', () => {
        get_current_pages_mock.mockReturnValue([
            { route: 'pages/material-list/index', options: { id: '1', title: '资料' } }
        ])
        show_modal_mock.mockImplementation((options) => {
            options.success({ confirm: true })
        })
        const { requireAction } = usePermission()
        const result = requireAction('view_material', () => {})
        expect(result).toBe(false)
        expect(show_modal_mock).toHaveBeenCalledTimes(1)
        expect(add_mock).toHaveBeenCalledWith('/pages/material-list/index?id=1&title=%E8%B5%84%E6%96%99')
        expect(navigate_to_mock).toHaveBeenCalledWith({ url: '/pages/login/index' })
    })
})

describe('getActionPermissionConfig', () => {
    it('未知 action 返回默认登录配置', () => {
        const result = getActionPermissionConfig('unknown_action', { content: 'x' })
        expect(result.permission_type).toBe('login')
        expect(result.options.content).toBe('x')
    })
})