feat(web): заготовка веб-клиента на Vite + React 19 + TypeScript strict
- стек по §5.2: React 19, React Router, TanStack Query, Zustand, Tailwind CSS 4, i18next (ru/en), Vitest + Testing Library - дизайн-токены §3 docs/client-web.md (тёмная тема по умолчанию, светлая, accent) - типизированный API-клиент §8.1: единый формат ошибок, ApiError с кодом - App: экран состояния фундамента с readz/meta, локализация ошибок по code - тесты: клиент API, форматирование, рендер App (успех/ошибка кода/сеть) - eslint + prettier + tsc strict; initial JS 97.6 KB gzip
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { App } from '@/App';
|
||||
import type { InstanceMeta } from '@/api/meta';
|
||||
import '@/i18n';
|
||||
|
||||
const meta: InstanceMeta = {
|
||||
name: 'glchat',
|
||||
version: 'v0.1.0-test',
|
||||
commit: 'deadbee',
|
||||
build_date: '2026-09-19T00:00:00Z',
|
||||
api_version: 'v1',
|
||||
base_url: 'https://gl.localhost',
|
||||
files_url: 'https://files.gl.localhost',
|
||||
gateway_url: 'wss://gl.localhost/gateway',
|
||||
rtc_path: '/rtc',
|
||||
max_upload_size: 26214400,
|
||||
features: {
|
||||
registration_enabled: true,
|
||||
anti_bot_enabled: false,
|
||||
voice_enabled: false,
|
||||
web_push_enabled: false,
|
||||
oauth_enabled: false,
|
||||
passkeys_enabled: false,
|
||||
},
|
||||
};
|
||||
|
||||
const readyBody = { status: 'ready', version: 'test', checks: { database: 'ok' } };
|
||||
|
||||
function json(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
function renderApp() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<App />
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('App', () => {
|
||||
it('renders instance metadata from the API', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn((input: RequestInfo | URL) => {
|
||||
const url = input instanceof Request ? input.url : String(input);
|
||||
return Promise.resolve(url.endsWith('/api/v1/meta') ? json(meta) : json(readyBody));
|
||||
}),
|
||||
);
|
||||
|
||||
renderApp();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('v0.1.0-test')).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText('v1')).toBeInTheDocument();
|
||||
expect(screen.getByText('25 MB')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('connection-state')).toHaveTextContent('Сервер доступен');
|
||||
});
|
||||
|
||||
it('localizes a server error by its code and offers a retry', async () => {
|
||||
const fetchMock = vi.fn(() =>
|
||||
json({ error: { code: 'internal.error', message: 'boom' } }, 500),
|
||||
);
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
renderApp();
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Внутренняя ошибка сервера.');
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
expect(screen.getByRole('button', { name: 'Повторить' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('falls back to a network message when the server is unreachable', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')));
|
||||
|
||||
renderApp();
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Сервер не отвечает');
|
||||
},
|
||||
{ timeout: 5000 },
|
||||
);
|
||||
expect(screen.getByTestId('connection-state')).toHaveTextContent('Сервер недоступен');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { ApiError, request } from '@/api/client';
|
||||
|
||||
function jsonResponse(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
describe('api client', () => {
|
||||
it('returns the parsed payload on success', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ api_version: 'v1' }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await expect(request<{ api_version: string }>('/meta')).resolves.toEqual({
|
||||
api_version: 'v1',
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/v1/meta',
|
||||
expect.objectContaining({ method: 'GET', credentials: 'same-origin' }),
|
||||
);
|
||||
});
|
||||
|
||||
it('maps the server error envelope to ApiError', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi
|
||||
.fn()
|
||||
.mockResolvedValue(
|
||||
jsonResponse({ error: { code: 'perm.denied', message: 'no access' } }, 403),
|
||||
),
|
||||
);
|
||||
|
||||
await expect(request('/guilds/1')).rejects.toMatchObject({
|
||||
name: 'ApiError',
|
||||
code: 'perm.denied',
|
||||
status: 403,
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to internal.error when the body is not an envelope', async () => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn().mockResolvedValue(new Response('gateway timeout', { status: 504 })),
|
||||
);
|
||||
|
||||
const error = await request('/meta').catch((reason: unknown) => reason);
|
||||
expect(error).toBeInstanceOf(ApiError);
|
||||
expect((error as ApiError).code).toBe('internal.error');
|
||||
expect((error as ApiError).status).toBe(504);
|
||||
});
|
||||
|
||||
it('sends a json body for write requests', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ ok: true }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await request('/guilds', { method: 'POST', body: { name: 'test' } });
|
||||
|
||||
const init = fetchMock.mock.calls[0]?.[1] as RequestInit;
|
||||
expect(init.body).toBe('{"name":"test"}');
|
||||
expect((init.headers as Record<string, string>)['Content-Type']).toBe('application/json');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { errorCode, formatBytes } from '@/lib/format';
|
||||
import { ApiError } from '@/api/client';
|
||||
|
||||
describe('formatBytes', () => {
|
||||
it('renders human readable sizes', () => {
|
||||
expect(formatBytes(512)).toBe('512 B');
|
||||
expect(formatBytes(1024)).toBe('1 KB');
|
||||
expect(formatBytes(26214400)).toBe('25 MB');
|
||||
expect(formatBytes(1073741824)).toBe('1 GB');
|
||||
});
|
||||
|
||||
it('handles invalid input', () => {
|
||||
expect(formatBytes(-1)).toBe('—');
|
||||
expect(formatBytes(Number.NaN)).toBe('—');
|
||||
});
|
||||
});
|
||||
|
||||
describe('errorCode', () => {
|
||||
it('extracts the server error code', () => {
|
||||
expect(errorCode(new ApiError(403, 'perm.denied', 'nope'))).toBe('perm.denied');
|
||||
});
|
||||
|
||||
it('maps unknown failures to a network code', () => {
|
||||
expect(errorCode(new Error('socket hang up'))).toBe('network.unreachable');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { afterEach, vi } from 'vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
// Globals stubbed with vi.stubGlobal must be dropped between tests,
|
||||
// otherwise a stub from one test leaks into the next one.
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
window.localStorage.clear();
|
||||
});
|
||||
Reference in New Issue
Block a user