Files
FitOS/admin/test/UserForm.test.tsx

370 lines
15 KiB
TypeScript

import { act, render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes, useParams } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import UserForm from '../src/pages/users/UserForm';
import { setAccessToken } from '../src/api/client';
import { API_BASE } from '../src/config';
import type { Gym, User } from '../src/api/types';
const GYM_A: Gym = {
id: 'gym-a',
name: 'Fit Factory',
location: 'Warszawa',
availability: null,
capacity: 10,
kind: 'REAL',
isPrivate: false,
equipment: [],
coverPhoto: null,
};
const GYM_B: Gym = {
id: 'gym-b',
name: 'Steel Gym',
location: 'Kraków',
availability: null,
capacity: null,
kind: 'REAL',
isPrivate: false,
equipment: [],
coverPhoto: null,
};
function emptyUser(over: Partial<User>): User {
return {
id: 'u1',
email: 'x@test.local',
firstName: null,
lastName: null,
nickname: null,
socialMedia: null,
birthDate: null,
heightCm: null,
phone: null,
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
status: 'ACTIVE',
suspensionUntil: null,
restrictionReason: null,
createdAt: '2026-08-01T10:00:00.000Z',
memberships: [],
...over,
};
}
const CREATED: User = emptyUser({ id: 'u9', email: 'nowy3@test.local', firstName: 'Nowy' });
const EDITED: User = emptyUser({
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
birthDate: '1996-05-05T00:00:00.000Z',
isAdmin: true,
memberships: [{ gymId: 'gym-a', roles: ['MEMBER'], gym: GYM_A }],
});
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
/** Mock wg fragmentu URL + metody; pierwsze pasujące (specyficzne przed ogólnymi). */
function mockRoutes(handlers: Array<{ method?: string; match: string; reply: () => unknown }>) {
const calls: { url: string; init?: RequestInit }[] = [];
const fetchMock = vi.fn(async (url: string, init?: RequestInit) => {
calls.push({ url, init });
const method = (init?.method ?? 'GET').toUpperCase();
const idx = handlers.findIndex(
(h) => (!h.method || h.method === method) && url.includes(h.match),
);
if (idx === -1) throw new Error(`No mocked route for ${method} ${url}`);
return jsonResponse(200, handlers[idx].reply());
});
vi.stubGlobal('fetch', fetchMock);
return calls;
}
function ParamId() {
const { id } = useParams();
return <>{id}</>;
}
function renderForm(path: string) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
return render(
<MemoryRouter initialEntries={[path]}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/users/new" element={<UserForm />} />
<Route path="/users/:id/edit" element={<UserForm />} />
<Route
path="/users/:id"
element={
<div>
DETAIL-
<ParamId />
</div>
}
/>
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
});
afterEach(() => {
vi.unstubAllGlobals();
});
/** Zapis via menu kontekstowe (topbar) nie istnieje w jednostkowym renderze —
* wymuszamy submit formularza dokładnie tak, jak robi to akcja „Zapisz”.
* Czekamy na pełny łańcuch async (PATCH → DELETE → nawigacja). */
async function submitForm() {
const form = document.querySelector('form');
if (!form) throw new Error('Brak formularza w DOM');
await act(async () => {
form.requestSubmit();
// czekaj na pełny łańcuch async: PATCH konta → DELETE/PATCH członkostw → nawigacja
for (let i = 0; i < 10; i++) await Promise.resolve();
});
}
describe('admin UserForm — kreator tworzenia', () => {
it('startuje bez siłowni (zachęta do pierwszej), a rola domyślnie niezaznaczona', async () => {
mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
{ match: '/admin/users', reply: () => ({ users: [] }) },
]);
const user = userEvent.setup();
renderForm('/users/new');
// stan pusty: brak wierszy, żadna rola, zachęta do dodania pierwszej siłowni
expect(await screen.findByText('Jeszcze bez siłowni')).toBeInTheDocument();
expect(screen.queryByRole('checkbox', { name: /siłownia 1/ })).not.toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Dodaj pierwszą siłownię' }));
expect(screen.getByText(/wybierz rolę, aby zobaczyć/i)).toBeInTheDocument();
await user.click(screen.getByRole('checkbox', { name: 'Ćwiczący — siłownia 1' }));
expect(
screen.getByText('Zwykły członek siłowni — trenuje i korzysta z planów.'),
).toBeInTheDocument();
// uprawnienia administratora platformy — rozwijane
await user.click(screen.getByRole('button', { name: /Pokaż uprawnienia admina/i }));
expect(
screen.getByText('Zarządzanie wszystkimi użytkownikami i siłowniami'),
).toBeInTheDocument();
});
it('tworzy użytkownika i przypisuje mu rolę w wybranej siłowni', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
{ method: 'POST', match: '/admin/users', reply: () => ({ user: CREATED }) },
{ method: 'POST', match: '/memberships', reply: () => ({ membership: {} }) },
]);
const user = userEvent.setup();
const { container } = renderForm('/users/new');
await user.type(container.querySelector('input[type="email"]')!, 'nowy3@test.local');
await user.type(container.querySelector('input[type="password"]')!, 'Password123!');
await user.type(container.querySelectorAll('input[type="password"]')[1], 'Password123!');
// wybierz siłownię (placeholder „Szukaj siłowni…”) i zaznacz rolę Trener
await user.click(screen.getByRole('button', { name: 'Dodaj pierwszą siłownię' }));
const gymBox = container.querySelector<HTMLInputElement>('input[role="combobox"]')!;
await user.click(gymBox);
await user.click(await screen.findByRole('option', { name: /Steel Gym/ }));
await user.click(await screen.findByRole('checkbox', { name: 'Trener — Steel Gym' }));
await submitForm();
expect(await screen.findByText('DETAIL-u9')).toBeInTheDocument();
const post = calls.find(
(c) => c.init?.method === 'POST' && c.url === `${API_BASE}/admin/users`,
);
expect(JSON.parse(post?.init?.body as string)).toMatchObject({
email: 'nowy3@test.local',
password: 'Password123!',
isAdmin: false,
});
const mem = calls.find(
(c) => c.init?.method === 'POST' && c.url.includes('/admin/users/u9/memberships'),
);
expect(JSON.parse(mem?.init?.body as string)).toEqual({
gymId: 'gym-b',
roles: ['TRAINER'],
});
});
it('blokuje zapis, gdy rola jest zaznaczona bez wybranej siłowni (modal)', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
{ method: 'POST', match: '/admin/users', reply: () => ({ user: CREATED }) },
{ method: 'POST', match: '/memberships', reply: () => ({ membership: {} }) },
]);
const user = userEvent.setup();
const { container } = renderForm('/users/new');
await user.type(container.querySelector('input[type="email"]')!, 'nowy4@test.local');
await user.type(container.querySelector('input[type="password"]')!, 'Password123!');
await user.type(container.querySelectorAll('input[type="password"]')[1], 'Password123!');
await user.click(screen.getByRole('button', { name: 'Dodaj pierwszą siłownię' }));
await user.click(screen.getByRole('checkbox', { name: 'Właściciel — siłownia 1' }));
await submitForm();
const dialog = await screen.findByRole('dialog');
expect(dialog).toHaveTextContent(/siłowni/);
expect(dialog).toHaveTextContent(/nie można zapisać/i);
// zapis zablokowany — żadne żądanie nie poszło
expect(calls.filter((c) => c.init?.method === 'POST')).toHaveLength(0);
});
it('blokuje zapis, gdy siłownia jest wybrana bez roli (modal)', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
{ method: 'POST', match: '/admin/users', reply: () => ({ user: CREATED }) },
{ method: 'POST', match: '/memberships', reply: () => ({ membership: {} }) },
]);
const user = userEvent.setup();
const { container } = renderForm('/users/new');
await user.type(container.querySelector('input[type="email"]')!, 'nowy5@test.local');
await user.type(container.querySelector('input[type="password"]')!, 'Password123!');
await user.type(container.querySelectorAll('input[type="password"]')[1], 'Password123!');
await user.click(screen.getByRole('button', { name: 'Dodaj pierwszą siłownię' }));
await user.click(container.querySelector('input[role="combobox"]')!);
await user.click(await screen.findByRole('option', { name: /Steel Gym/ }));
await submitForm();
const dialog = screen.getByRole('dialog');
expect(dialog).toHaveTextContent(/bez roli/i);
expect(calls.filter((c) => c.init?.method === 'POST')).toHaveLength(0);
await user.click(within(dialog).getByRole('button', { name: 'Rozumiem' }));
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
it('blokuje zapis, gdy powtórzone hasło różni się od hasła', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A] }) },
{ method: 'POST', match: '/admin/users', reply: () => ({ user: CREATED }) },
]);
const user = userEvent.setup();
const { container } = renderForm('/users/new');
const pw = container.querySelectorAll('input[type="password"]');
await user.type(container.querySelector('input[type="email"]')!, 'nowy6@test.local');
await user.type(pw[0], 'Password123!');
await user.type(pw[1], 'InneHaslo123!');
await submitForm();
expect(await screen.findByText('Podane hasła muszą być takie same.')).toBeInTheDocument();
expect(calls.filter((c) => c.init?.method === 'POST')).toHaveLength(0);
});
});
describe('admin UserForm — kreator edycji', () => {
it('wypełnia formularz danymi konta i członkostwami (edytor w wizardzie)', async () => {
mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
{ match: '/admin/users', reply: () => ({ users: [EDITED] }) },
]);
const { container } = renderForm('/users/u1/edit');
// dane i członkostwo wczytane z użytkownika — krok 3 jest też w edycji
expect(await screen.findByDisplayValue('Jan')).toBeInTheDocument();
// w edycji e-mail zamaskowany i tylko do odczytu (pełny adres zna tylko user)
const emailInput = container.querySelector('input[type="email"]');
expect(emailInput).toBeNull();
const masked = container.querySelector('input[readonly]') as HTMLInputElement | null;
expect(masked?.value).toBe('j*n@t***.local');
expect(screen.getByDisplayValue('1996-05-05')).toBeInTheDocument();
expect(await screen.findByText('Członkostwa w siłowniach')).toBeInTheDocument();
expect(screen.getByDisplayValue('Fit Factory')).toBeInTheDocument();
});
it('zapis edycji bez zmian członkostw PATCHuje tylko konto', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
{ method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) },
{ match: '/admin/users', reply: () => ({ users: [EDITED] }) },
]);
const user = userEvent.setup();
renderForm('/users/u1/edit');
await screen.findByDisplayValue('Jan');
// edycja = tożsamość/dostęp: zmiana nazwiska; skłon ról bez zmian = zero żądań członkostw
const inputs = document.querySelectorAll('input');
await user.clear(inputs[1]);
await user.type(inputs[1], 'Nowak');
await submitForm();
expect(await screen.findByText('DETAIL-u1')).toBeInTheDocument();
const accountPatch = calls.find(
(c) => c.init?.method === 'PATCH' && c.url === `${API_BASE}/admin/users/u1`,
);
// e-mail niewidoczny w formularzu, ale PATCH przenosi go bez zmian
expect(JSON.parse(accountPatch?.init?.body as string)).toMatchObject({
lastName: 'Nowak',
email: 'jan@test.local',
isAdmin: true,
});
expect(calls.some((c) => c.url.includes('/memberships'))).toBe(false);
});
it('zapis edycji PATCHuje konto i zmianę roli członkostwa', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
{ method: 'PATCH', match: '/memberships/gym-a', reply: () => ({ membership: {} }) },
{ method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) },
{ match: '/admin/users', reply: () => ({ users: [EDITED] }) },
]);
const user = userEvent.setup();
renderForm('/users/u1/edit');
await screen.findByDisplayValue('Fit Factory');
// dołóż rolę Właściciel do istniejącego członkostwa (MEMBER → MEMBER + OWNER)
await user.click(screen.getByRole('checkbox', { name: 'Właściciel — Fit Factory' }));
await submitForm();
expect(await screen.findByText('DETAIL-u1')).toBeInTheDocument();
const accountPatch = calls.find(
(c) => c.init?.method === 'PATCH' && c.url === `${API_BASE}/admin/users/u1`,
);
expect(JSON.parse(accountPatch?.init?.body as string)).toMatchObject({ isAdmin: true });
const memPatch = calls.find(
(c) => c.init?.method === 'PATCH' && c.url.includes('/memberships/gym-a'),
);
expect(JSON.parse(memPatch?.init?.body as string)).toEqual({ roles: ['MEMBER', 'OWNER'] });
});
it('usunięcie wiersza członkostwa wysyła DELETE', async () => {
const calls = mockRoutes([
{ match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) },
{ method: 'PATCH', match: '/admin/users/u1', reply: () => ({ user: EDITED }) },
{ method: 'DELETE', match: '/memberships/gym-a', reply: () => ({}) },
{ match: '/admin/users', reply: () => ({ users: [EDITED] }) },
]);
const user = userEvent.setup();
renderForm('/users/u1/edit');
await screen.findByDisplayValue('Fit Factory');
await user.click(screen.getByRole('button', { name: 'Usuń Fit Factory' }));
await submitForm();
const del = calls.find(
(c) => c.init?.method === 'DELETE' && c.url.includes('/memberships/gym-a'),
);
expect(del).toBeDefined();
});
});