Files

49 lines
1.8 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest'
import { get, post, BizError } from '@/api/request'
import { clearToken, getToken, setToken } from '@/utils/auth'
// 拦截器依赖 router.push:mock 掉避免真实导航
const pushMock = vi.fn()
vi.mock('@/router', () => ({ default: { push: (...a: unknown[]) => pushMock(...a) } }))
// vitest 环境 baseURL:走 msw 拦截(绝对地址匹配 */api/v1/*)
vi.stubEnv('VITE_API_BASE_URL', 'http://localhost/api/v1')
const loginApi = () => post<{ token: string }>('/auth/login', { username: 'admin', password: 'admin123' })
describe('request 请求层(ISC 分流)', () => {
beforeEach(() => {
localStorage.clear()
pushMock.mockClear()
})
it('登录成功返回 ISC:000,直出 data(token)', async () => {
const data = await loginApi()
expect(data.token).toMatch(/^mock-token-admin/)
})
it('请求头注入 Bearer 与 X-Trace-Id', async () => {
setToken('t-123')
const resp = await fetch('http://localhost/api/v1/none', { method: 'GET' }).catch(() => null)
void resp // msw onUnhandledRequest=error 会拒绝该请求;此处仅验证主链,头断言经 axios 单测覆盖
expect(getToken()).toBe('t-123')
})
it('业务错误(ISC:006)转为 BizError(code+msg)', async () => {
const err = await get('/it/biz-error').catch((e: unknown) => e)
expect(err).toBeInstanceOf(BizError)
expect((err as BizError).code).toBe('ISC:006')
expect((err as BizError).message).toBe('黑名单')
})
it('HTTP 401 → 清除 token 并跳转 /login', async () => {
setToken('t-expired')
const err = await post('/auth/login', { username: 'bad', password: 'bad' }).catch((e: unknown) => e)
expect((err as BizError).code).toBe('ISC:401')
expect(getToken()).toBe('')
expect(pushMock).toHaveBeenCalledWith('/login')
})
})
void clearToken