完成JC-ArtList与JC-Salon端侧清理和统一命名
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { isApiAuthFreePath, WEB_API_AUTH_FREE_PATHS } from '@/api/auth-free-paths'
|
||||
|
||||
describe('auth-free API contract', () => {
|
||||
it('covers public paths and rejects protected business APIs', () => {
|
||||
expect(isApiAuthFreePath('/comment/list/product/1')).toBe(true)
|
||||
expect(isApiAuthFreePath('/user/wechat-mini/auto-login')).toBe(true)
|
||||
expect(isApiAuthFreePath('/nail-artist/profile/1')).toBe(true)
|
||||
expect(isApiAuthFreePath('/nail-artist/1/availability')).toBe(true)
|
||||
expect(isApiAuthFreePath('/nail-artist/1/reviews')).toBe(true)
|
||||
expect(isApiAuthFreePath('/shop/list')).toBe(true)
|
||||
|
||||
expect(isApiAuthFreePath('/order/list')).toBe(false)
|
||||
expect(isApiAuthFreePath('/shop/delete/1')).toBe(false)
|
||||
expect(isApiAuthFreePath('/permission/list')).toBe(false)
|
||||
expect(isApiAuthFreePath('/order/list?next=/user/login')).toBe(false)
|
||||
expect(isApiAuthFreePath('/user/profile/admin/auth/refresh')).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps auth-free path constants unique', () => {
|
||||
expect(new Set(WEB_API_AUTH_FREE_PATHS).size).toBe(WEB_API_AUTH_FREE_PATHS.length)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,124 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const messageError = vi.hoisted(() => vi.fn())
|
||||
const modalError = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('ant-design-vue', () => ({
|
||||
message: {
|
||||
error: messageError
|
||||
},
|
||||
Modal: {
|
||||
error: modalError
|
||||
}
|
||||
}))
|
||||
|
||||
import api from '../../src/api'
|
||||
|
||||
function createTokenExpiredError(config: InternalAxiosRequestConfig) {
|
||||
const response = {
|
||||
data: {
|
||||
code: 401,
|
||||
message: 'Token expired'
|
||||
},
|
||||
status: 401,
|
||||
statusText: 'Unauthorized',
|
||||
headers: {},
|
||||
config,
|
||||
request: {}
|
||||
} as AxiosResponse
|
||||
|
||||
return new AxiosError(
|
||||
'Request failed with status code 401',
|
||||
AxiosError.ERR_BAD_REQUEST,
|
||||
config,
|
||||
{},
|
||||
response
|
||||
)
|
||||
}
|
||||
|
||||
describe('api stale token handling', () => {
|
||||
const originalAdapter = api.defaults.adapter
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
messageError.mockClear()
|
||||
modalError.mockClear()
|
||||
window.history.replaceState(null, '', '/profile')
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
api.defaults.adapter = originalAdapter
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('keeps a newer login session when an old-token request returns 401', async () => {
|
||||
localStorage.setItem('accessToken', 'old-token')
|
||||
sessionStorage.setItem('accessToken', 'old-token')
|
||||
|
||||
const requests: Array<{ url?: string, authorization?: string }> = []
|
||||
let markRequestStarted!: () => void
|
||||
let releaseStale401!: () => void
|
||||
const requestStarted = new Promise<void>(resolve => {
|
||||
markRequestStarted = resolve
|
||||
})
|
||||
|
||||
api.defaults.adapter = ((config: InternalAxiosRequestConfig) => {
|
||||
if (config.url !== '/user/info') {
|
||||
return Promise.reject(new Error(`Unexpected request: ${config.url}`))
|
||||
}
|
||||
|
||||
requests.push({
|
||||
url: config.url,
|
||||
authorization: String(config.headers.Authorization || '')
|
||||
})
|
||||
markRequestStarted()
|
||||
|
||||
return new Promise((_resolve, reject) => {
|
||||
releaseStale401 = () => reject(createTokenExpiredError(config))
|
||||
})
|
||||
}) as AxiosAdapter
|
||||
|
||||
const staleRequest = api.get('/user/info')
|
||||
|
||||
await requestStarted
|
||||
expect(requests).toEqual([
|
||||
{
|
||||
url: '/user/info',
|
||||
authorization: 'Bearer old-token'
|
||||
}
|
||||
])
|
||||
|
||||
localStorage.setItem('accessToken', 'new-token')
|
||||
localStorage.setItem('refreshToken', 'new-refresh')
|
||||
localStorage.setItem('userInfo', JSON.stringify({ id: 2, nickname: 'new-user' }))
|
||||
sessionStorage.setItem('accessToken', 'new-token')
|
||||
sessionStorage.setItem('refreshToken', 'new-refresh')
|
||||
const hrefBefore401 = window.location.href
|
||||
|
||||
releaseStale401()
|
||||
|
||||
await expect(staleRequest).rejects.toMatchObject({
|
||||
response: {
|
||||
status: 401
|
||||
}
|
||||
})
|
||||
await vi.runAllTimersAsync()
|
||||
|
||||
expect(requests).toHaveLength(1)
|
||||
expect(localStorage.getItem('accessToken')).toBe('new-token')
|
||||
expect(localStorage.getItem('refreshToken')).toBe('new-refresh')
|
||||
expect(localStorage.getItem('userInfo')).toBe(JSON.stringify({ id: 2, nickname: 'new-user' }))
|
||||
expect(sessionStorage.getItem('accessToken')).toBe('new-token')
|
||||
expect(sessionStorage.getItem('refreshToken')).toBe('new-refresh')
|
||||
expect(window.location.href).toBe(hrefBefore401)
|
||||
expect(messageError).not.toHaveBeenCalled()
|
||||
expect(modalError).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,146 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const messageError = vi.hoisted(() => vi.fn())
|
||||
const modalError = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('ant-design-vue', () => ({
|
||||
message: {
|
||||
error: messageError
|
||||
},
|
||||
Modal: {
|
||||
error: modalError
|
||||
}
|
||||
}))
|
||||
|
||||
import api from '../../src/api'
|
||||
|
||||
const createResponseError = (config: InternalAxiosRequestConfig, status: number): AxiosError => {
|
||||
const response = {
|
||||
data: {
|
||||
code: status,
|
||||
message: `HTTP ${status}`
|
||||
},
|
||||
status,
|
||||
statusText: 'Error',
|
||||
headers: {},
|
||||
config,
|
||||
request: {}
|
||||
} as AxiosResponse
|
||||
|
||||
return new AxiosError(
|
||||
`Request failed with status code ${status}`,
|
||||
AxiosError.ERR_BAD_RESPONSE,
|
||||
config,
|
||||
{},
|
||||
response
|
||||
)
|
||||
}
|
||||
|
||||
const createNetworkError = (config: InternalAxiosRequestConfig): AxiosError =>
|
||||
new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, {})
|
||||
|
||||
type MockRequestResult = AxiosError | null
|
||||
|
||||
const mockRequestResults = (results: MockRequestResult[]) => {
|
||||
let currentResultIndex = 0
|
||||
api.defaults.adapter = ((config: InternalAxiosRequestConfig) => {
|
||||
const result = results[currentResultIndex]
|
||||
currentResultIndex += 1
|
||||
if (!result) {
|
||||
return Promise.resolve({
|
||||
data: { code: 200, data: { ok: true } },
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: {},
|
||||
config,
|
||||
request: {}
|
||||
} as AxiosResponse)
|
||||
}
|
||||
result.config = config
|
||||
return Promise.reject(result)
|
||||
}) as AxiosAdapter
|
||||
}
|
||||
|
||||
describe('api system unavailable handling', () => {
|
||||
const originalAdapter = api.defaults.adapter
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(1_000)
|
||||
messageError.mockClear()
|
||||
modalError.mockClear()
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
api.defaults.adapter = originalAdapter
|
||||
localStorage.clear()
|
||||
sessionStorage.clear()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('shows one system unavailable modal after three server failures in the window', async () => {
|
||||
const config = {} as InternalAxiosRequestConfig
|
||||
mockRequestResults([
|
||||
createResponseError(config, 500),
|
||||
createResponseError(config, 502),
|
||||
createResponseError(config, 503),
|
||||
createResponseError(config, 500)
|
||||
])
|
||||
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 502 } })
|
||||
expect(modalError).not.toHaveBeenCalled()
|
||||
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 503 } })
|
||||
expect(modalError).toHaveBeenCalledTimes(1)
|
||||
expect(modalError).toHaveBeenCalledWith(expect.objectContaining({
|
||||
title: '系统暂不可用',
|
||||
content: '当前服务暂时无法响应,请稍后重试。如问题持续存在,请联系管理员。',
|
||||
okText: '我知道了'
|
||||
}))
|
||||
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
expect(modalError).toHaveBeenCalledTimes(1)
|
||||
modalError.mock.calls[0]?.[0]?.afterClose?.()
|
||||
})
|
||||
|
||||
it('counts network failures as system failures', async () => {
|
||||
const config = {} as InternalAxiosRequestConfig
|
||||
vi.setSystemTime(70_000)
|
||||
mockRequestResults([
|
||||
createNetworkError(config),
|
||||
createNetworkError(config),
|
||||
createNetworkError(config)
|
||||
])
|
||||
|
||||
await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError)
|
||||
await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError)
|
||||
await expect(api.get('/health')).rejects.toBeInstanceOf(AxiosError)
|
||||
|
||||
expect(modalError).toHaveBeenCalledTimes(1)
|
||||
expect(messageError).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('resets failure count after a successful response', async () => {
|
||||
const config = {} as InternalAxiosRequestConfig
|
||||
vi.setSystemTime(140_000)
|
||||
mockRequestResults([
|
||||
createResponseError(config, 500),
|
||||
createResponseError(config, 500),
|
||||
null,
|
||||
createResponseError(config, 500)
|
||||
])
|
||||
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
await expect(api.get('/health')).resolves.toEqual({ ok: true })
|
||||
await expect(api.get('/health')).rejects.toMatchObject({ response: { status: 500 } })
|
||||
|
||||
expect(modalError).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user