React 19 + Vite 6 + Router 7 + TanStack Query + Zustand;Semi 二次封装与 Remix 图标统一出口;顶部模块 + 左侧功能菜单布局、Cloud Blue 主题、登录页与 401/403/404/500 页面;请求层含 token 注入、单飞刷新与统一错误提示。
142 lines
4.9 KiB
TypeScript
142 lines
4.9 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
|
|
import { useAuthStore } from '@/stores/auth-store';
|
|
|
|
import { ApiError, request, setUnauthorizedHandler } from './client';
|
|
|
|
const jsonResponse = (body: unknown, status = 200): Response =>
|
|
new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
|
|
const emptyResponse = (status: number): Response => new Response(null, { status });
|
|
|
|
function signIn(accessToken = 'token-1', refreshToken = 'refresh-1'): void {
|
|
useAuthStore.getState().setSession({
|
|
accessToken,
|
|
refreshToken,
|
|
user: { id: '01J0TEST000000000000000000', name: '测试用户', email: 'test@lingxi.local' },
|
|
permissions: [],
|
|
});
|
|
}
|
|
|
|
function authorizationOf(init: RequestInit | undefined): string | null {
|
|
return init?.headers instanceof Headers ? init.headers.get('Authorization') : null;
|
|
}
|
|
|
|
function toUrl(input: string | URL | Request | undefined): string {
|
|
if (typeof input === 'string') {
|
|
return input;
|
|
}
|
|
if (input instanceof URL) {
|
|
return input.href;
|
|
}
|
|
return input?.url ?? '';
|
|
}
|
|
|
|
describe('请求层', () => {
|
|
beforeEach(() => {
|
|
vi.restoreAllMocks();
|
|
window.localStorage.clear();
|
|
useAuthStore.getState().clearSession();
|
|
setUnauthorizedHandler(null);
|
|
});
|
|
|
|
it('注入 Bearer token 并解析 JSON', async () => {
|
|
signIn();
|
|
const fetchMock = vi
|
|
.spyOn(globalThis, 'fetch')
|
|
.mockResolvedValue(jsonResponse({ status: 'ok' }));
|
|
|
|
await expect(request<{ status: string }>('/health')).resolves.toEqual({ status: 'ok' });
|
|
const init = fetchMock.mock.calls[0]?.[1];
|
|
expect(authorizationOf(init)).toBe('Bearer token-1');
|
|
expect(toUrl(fetchMock.mock.calls[0]?.[0])).toBe('http://127.0.0.1:3000/api/v1/health');
|
|
});
|
|
|
|
it('auth: false 时不注入 token', async () => {
|
|
signIn();
|
|
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ ok: true }));
|
|
await request('/auth/login', {
|
|
method: 'POST',
|
|
auth: false,
|
|
body: { email: 'a', password: 'b' },
|
|
});
|
|
expect(authorizationOf(fetchMock.mock.calls[0]?.[1])).toBeNull();
|
|
});
|
|
|
|
it('204 返回 undefined', async () => {
|
|
signIn();
|
|
vi.spyOn(globalThis, 'fetch').mockResolvedValue(emptyResponse(204));
|
|
await expect(request('/resource')).resolves.toBeUndefined();
|
|
});
|
|
|
|
it('统一错误体解析为 ApiError,保留 trace_id', async () => {
|
|
signIn();
|
|
vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
|
jsonResponse(
|
|
{ code: 42201, message: '业务校验失败', details: { field: 'name' }, trace_id: 'trace-1' },
|
|
422,
|
|
),
|
|
);
|
|
const error = await request('/resource').catch((caught: unknown) => caught);
|
|
expect(error).toBeInstanceOf(ApiError);
|
|
const apiError = error instanceof ApiError ? error : null;
|
|
expect(apiError?.code).toBe(42201);
|
|
expect(apiError?.status).toBe(422);
|
|
expect(apiError?.traceId).toBe('trace-1');
|
|
expect(apiError?.details).toEqual({ field: 'name' });
|
|
});
|
|
|
|
it('401 时单飞刷新并重放原请求', async () => {
|
|
signIn('expired-token', 'refresh-1');
|
|
let refreshCalls = 0;
|
|
vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => {
|
|
const url = toUrl(input);
|
|
const authorization = authorizationOf(init);
|
|
if (url.endsWith('/auth/refresh')) {
|
|
refreshCalls += 1;
|
|
return Promise.resolve(
|
|
jsonResponse({ accessToken: 'new-token', refreshToken: 'refresh-2' }),
|
|
);
|
|
}
|
|
if (authorization === 'Bearer expired-token') {
|
|
return Promise.resolve(emptyResponse(401));
|
|
}
|
|
return Promise.resolve(jsonResponse({ ok: true }));
|
|
});
|
|
|
|
const [first, second] = await Promise.all([request('/a'), request('/b')]);
|
|
expect(first).toEqual({ ok: true });
|
|
expect(second).toEqual({ ok: true });
|
|
expect(refreshCalls).toBe(1);
|
|
expect(useAuthStore.getState().accessToken).toBe('new-token');
|
|
});
|
|
|
|
it('刷新失败时清空会话并触发未授权回调', async () => {
|
|
signIn('expired-token', 'refresh-1');
|
|
const onUnauthorized = vi.fn();
|
|
setUnauthorizedHandler(onUnauthorized);
|
|
vi.spyOn(globalThis, 'fetch').mockImplementation((input) => {
|
|
const url = toUrl(input);
|
|
return Promise.resolve(
|
|
url.endsWith('/auth/refresh') ? emptyResponse(401) : emptyResponse(401),
|
|
);
|
|
});
|
|
|
|
await expect(request('/secure')).rejects.toBeInstanceOf(ApiError);
|
|
expect(onUnauthorized).toHaveBeenCalledTimes(1);
|
|
expect(useAuthStore.getState().accessToken).toBeNull();
|
|
});
|
|
|
|
it('把请求体序列化为 JSON', async () => {
|
|
signIn();
|
|
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue(jsonResponse({ ok: true }));
|
|
await request('/resource', { method: 'POST', body: { name: '素材' } });
|
|
const init = fetchMock.mock.calls[0]?.[1];
|
|
expect(init?.body).toBe(JSON.stringify({ name: '素材' }));
|
|
expect(init?.method).toBe('POST');
|
|
});
|
|
});
|