CI / build-and-test (push) Canceled after 0s
以 ckcloudManage a44810c 为基础,只保留资产页面(台账、单据、基础数据、同步任务)、 登录/错误/个人资料等公共页面,以及资产单据“查看流程”用到的流程详情页; 统一登录应用编码默认 CK_ASSET,标题“资产管理”,本地端口 9090。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
204 lines
8.3 KiB
TypeScript
204 lines
8.3 KiB
TypeScript
import { Blob as NodeBlob } from 'node:buffer'
|
|
import axios, { type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
|
import { ElMessage, ElNotification } from 'element-plus'
|
|
import request from '@/config/axios'
|
|
import { service } from '@/config/axios/service'
|
|
import { getAuthSession, setToken, withAuthSessionLock } from '@/utils/auth'
|
|
import type { TokenType } from '@/api/login/types'
|
|
|
|
vi.mock('element-plus', async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import('element-plus')>()
|
|
return {
|
|
...actual,
|
|
ElMessage: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn() }),
|
|
ElNotification: Object.assign(vi.fn(), { error: vi.fn(), info: vi.fn() }),
|
|
ElMessageBox: Object.assign(vi.fn(), { alert: vi.fn().mockResolvedValue(undefined) })
|
|
}
|
|
})
|
|
|
|
vi.mock('@/utils/sessionReplaced', () => ({
|
|
checkSessionReplaced: vi.fn().mockResolvedValue(false),
|
|
isSessionReplacedNoticeOpen: vi.fn().mockReturnValue(false),
|
|
showSessionReplacedNotice: vi.fn().mockResolvedValue(undefined)
|
|
}))
|
|
|
|
const token = (access: string, refresh = 'refresh-1'): TokenType => ({
|
|
id: 1,
|
|
accessToken: access,
|
|
refreshToken: refresh,
|
|
userId: 1,
|
|
userType: 2,
|
|
clientId: 'ckcloud',
|
|
expiresTime: Date.now() + 60_000
|
|
})
|
|
|
|
const login = (access = 'access-1', refresh = 'refresh-1') =>
|
|
withAuthSessionLock(() => setToken(token(access, refresh), 'session-1'))
|
|
|
|
type Responder = (config: InternalAxiosRequestConfig) => Partial<AxiosResponse> | Promise<Partial<AxiosResponse>>
|
|
|
|
/** 用自定义 adapter 代替网络层,记录每次请求的配置 */
|
|
const mockAdapter = (responder: Responder) => {
|
|
const calls: InternalAxiosRequestConfig[] = []
|
|
const adapter: AxiosAdapter = async (config) => {
|
|
calls.push(config)
|
|
const partial = await responder(config)
|
|
return {
|
|
status: 200,
|
|
statusText: 'OK',
|
|
headers: {},
|
|
config,
|
|
request: { responseType: config.responseType },
|
|
data: undefined,
|
|
...partial
|
|
} as AxiosResponse
|
|
}
|
|
service.defaults.adapter = adapter
|
|
return calls
|
|
}
|
|
|
|
describe('config/axios 请求封装', () => {
|
|
it('携带访问令牌,GET 禁用缓存,成功时返回 data 字段', async () => {
|
|
await login()
|
|
const calls = mockAdapter(() => ({ data: { code: 200, data: { id: 7 } } }))
|
|
const result = await request.get<{ id: number }>({ url: '/system/user/get', params: { id: 7 } })
|
|
expect(result).toEqual({ id: 7 })
|
|
expect(calls[0].headers.Authorization).toBe('Bearer access-1')
|
|
expect(calls[0].headers['Cache-Control']).toBe('no-cache')
|
|
expect(calls[0].params).toEqual({ id: 7 })
|
|
})
|
|
|
|
it('白名单接口与 isToken=false 不带令牌', async () => {
|
|
await login()
|
|
const calls = mockAdapter(() => ({ data: { code: 200, data: true } }))
|
|
await request.post({ url: '/system/auth/login', data: {} })
|
|
await request.get({ url: '/public', headers: { isToken: false } })
|
|
expect(calls[0].headers.Authorization).toBeUndefined()
|
|
expect(calls[1].headers.Authorization).toBeUndefined()
|
|
})
|
|
|
|
it('表单编码的 POST 自动序列化请求体', async () => {
|
|
await login()
|
|
const calls = mockAdapter(() => ({ data: { code: 200, data: null } }))
|
|
await request.post({
|
|
url: '/x',
|
|
data: { a: 1, b: 'c' },
|
|
headersType: 'application/x-www-form-urlencoded'
|
|
})
|
|
expect(calls[0].data).toBe('a=1&b=c')
|
|
})
|
|
|
|
it('业务错误码:500 提示通用错误,403 提示刷新,其他码通知后台消息', async () => {
|
|
await login()
|
|
mockAdapter((config) => {
|
|
if (config.url === '/e500') return { data: { code: 500, msg: '内部错误' } }
|
|
if (config.url === '/e403') return { data: { code: 403, msg: '没有权限' } }
|
|
return { data: { code: 1002, msg: '用户名已存在' } }
|
|
})
|
|
await expect(request.get({ url: '/e500' })).rejects.toThrow('内部错误')
|
|
expect(ElMessage.error).toHaveBeenCalled()
|
|
await expect(request.get({ url: '/e403' })).rejects.toMatchObject({ status: 403 })
|
|
expect(ElNotification.error).toHaveBeenCalledWith({ title: '没有权限,权限可能已调整,请刷新页面' })
|
|
await expect(request.get({ url: '/e1002' })).rejects.toThrow('用户名已存在')
|
|
expect(ElNotification.error).toHaveBeenCalledWith({ title: '用户名已存在' })
|
|
})
|
|
|
|
it('无后台消息时按错误码表兜底', async () => {
|
|
await login()
|
|
mockAdapter(() => ({ data: { code: 404 } }))
|
|
await expect(request.get({ url: '/missing' })).rejects.toThrow('访问资源不存在')
|
|
})
|
|
|
|
it('401 时用刷新令牌续期并以新令牌重试原请求', async () => {
|
|
await login('old-access', 'refresh-1')
|
|
// 后端续期只换发访问令牌,刷新令牌保持不变
|
|
const post = vi.spyOn(axios, 'post').mockResolvedValue({
|
|
data: { code: 0, data: token('new-access', 'refresh-1') }
|
|
})
|
|
const calls = mockAdapter((config) =>
|
|
config.headers.Authorization === 'Bearer new-access'
|
|
? { data: { code: 200, data: 'ok' } }
|
|
: { data: { code: 401, msg: '未登录' } }
|
|
)
|
|
await expect(request.get({ url: '/system/user/page' })).resolves.toBe('ok')
|
|
expect(post).toHaveBeenCalledOnce()
|
|
expect(post.mock.calls[0][0]).toContain('/system/auth/refresh-token')
|
|
expect(post.mock.calls[0][2]?.params).toEqual({ refreshToken: 'refresh-1' })
|
|
expect(calls).toHaveLength(2)
|
|
expect(getAuthSession()).toMatchObject({ accessToken: 'new-access', refreshToken: 'refresh-1' })
|
|
})
|
|
|
|
it('并发 401 只续期一次', async () => {
|
|
await login('old-access', 'refresh-1')
|
|
const post = vi.spyOn(axios, 'post').mockImplementation(
|
|
() =>
|
|
new Promise((resolve) =>
|
|
setTimeout(() => resolve({ data: { code: 200, data: token('new-access', 'refresh-1') } }), 5)
|
|
)
|
|
)
|
|
mockAdapter((config) =>
|
|
config.headers.Authorization === 'Bearer new-access'
|
|
? { data: { code: 200, data: config.url } }
|
|
: { data: { code: 401 } }
|
|
)
|
|
const results = await Promise.all([
|
|
request.get({ url: '/a' }),
|
|
request.get({ url: '/b' }),
|
|
request.get({ url: '/c' })
|
|
])
|
|
expect(results).toEqual(['/a', '/b', '/c'])
|
|
expect(post).toHaveBeenCalledTimes(1)
|
|
})
|
|
|
|
it('刷新令牌失效时清除本地会话并拒绝请求', async () => {
|
|
await login('old-access', 'refresh-1')
|
|
vi.spyOn(axios, 'post').mockResolvedValue({ data: { code: 401, msg: '刷新令牌已过期' } })
|
|
mockAdapter(() => ({ data: { code: 401 } }))
|
|
await expect(request.get({ url: '/x' })).rejects.toThrow('登录状态已失效,请重新登录')
|
|
await vi.waitFor(() => expect(getAuthSession().accessToken).toBe(''))
|
|
})
|
|
|
|
it('skipAuthRefresh 的 401 直接失败,不续期', async () => {
|
|
await login()
|
|
const post = vi.spyOn(axios, 'post')
|
|
mockAdapter(() => ({ data: { code: 401, msg: '未登录' } }))
|
|
await expect(request.get({ url: '/x', skipAuthRefresh: true })).rejects.toThrow('未登录')
|
|
expect(post).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('下载:二进制响应原样返回,JSON 错误体按业务错误处理', async () => {
|
|
await login()
|
|
const file = new Blob(['a,b'], { type: 'application/vnd.ms-excel' })
|
|
mockAdapter((config) =>
|
|
config.url === '/export-ok'
|
|
? { data: file }
|
|
: {
|
|
// 用 Node 的 Blob,便于源码中 new Response(blob).json() 读取(jsdom 的 Blob 不被 undici 识别)
|
|
data: new NodeBlob([JSON.stringify({ code: 1001, msg: '导出失败' })], {
|
|
type: 'application/json'
|
|
})
|
|
}
|
|
)
|
|
await expect(request.download({ url: '/export-ok' })).resolves.toBe(file)
|
|
await expect(request.download({ url: '/export-bad' })).rejects.toThrow('导出失败')
|
|
})
|
|
|
|
it('网络异常与超时给出中文提示', async () => {
|
|
await login()
|
|
service.defaults.adapter = async () => {
|
|
throw new axios.AxiosError('timeout of 30000ms exceeded', 'ECONNABORTED')
|
|
}
|
|
await expect(request.get({ url: '/slow' })).rejects.toThrow('timeout')
|
|
expect(ElMessage.error).toHaveBeenCalled()
|
|
})
|
|
|
|
it('会话已被其他标签页替换时拒绝旧请求结果', async () => {
|
|
await login('access-1', 'refresh-1')
|
|
mockAdapter(async () => {
|
|
await withAuthSessionLock(() => setToken(token('access-2', 'refresh-9'), 'session-2'))
|
|
return { data: { code: 200, data: 'stale' } }
|
|
})
|
|
await expect(request.get({ url: '/x' })).rejects.toThrow('登录会话已变更')
|
|
})
|
|
})
|