import { act, render, screen } 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 { return { id: 'u1', email: 'x@test.local', firstName: null, lastName: null, nickname: null, socialMedia: null, age: null, heightCm: null, phone: null, isAdmin: false, availability: null, priorities: null, exclusions: null, developMuscles: [], canDoMuscles: [], difficultMuscles: [], avoidMuscles: [], 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', age: 30, 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( } /> } /> DETAIL- } /> , ); } 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('wyjaśnia role i pokazuje uprawnienia administratora po rozwinięciu', async () => { mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { match: '/admin/users', reply: () => ({ users: [] }) }, ]); const user = userEvent.setup(); renderForm('/users/new'); expect(await screen.findByRole('heading', { name: 'Nowy użytkownik' })).toBeInTheDocument(); // role siłowni opisane w domyślnie zaznaczonej roli (Ćwiczący) expect( screen.getByText('Zwykły członek siłowni — trenuje i korzysta z planów.'), ).toBeInTheDocument(); 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!'); // wybierz siłownię (placeholder „Szukaj siłowni…”) i dołóż rolę Trener const gymBox = container.querySelector('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: ['MEMBER', 'TRAINER'], }); }); it('blokuje ostatnią rolę w wierszu (nie da się odznaczyć jedynej)', async () => { mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A] }) }, { match: '/admin/users', reply: () => ({ users: [] }) }, ]); renderForm('/users/new'); const member = await screen.findByRole('checkbox', { name: 'Ćwiczący — siłownia 1' }); expect(member).toBeChecked(); expect(member).toBeDisabled(); }); }); describe('admin UserForm — kreator edycji', () => { it('wypełnia formularz danymi użytkownika i jego członkostwami', async () => { mockRoutes([ { match: '/admin/gyms', reply: () => ({ gyms: [GYM_A, GYM_B] }) }, { match: '/admin/users', reply: () => ({ users: [EDITED] }) }, ]); renderForm('/users/u1/edit'); expect(await screen.findByRole('heading', { name: 'Edycja użytkownika' })).toBeInTheDocument(); // dane i członkostwo wczytane z użytkownika expect(await screen.findByDisplayValue('jan@test.local')).toBeInTheDocument(); expect(await screen.findByDisplayValue('Jan')).toBeInTheDocument(); expect(screen.getByDisplayValue('Fit Factory')).toBeInTheDocument(); }); 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: '/memberships/gym-a', reply: () => ({ membership: {} }) }, { 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ń wiersz siłowni 1' })); await submitForm(); const del = calls.find( (c) => c.init?.method === 'DELETE' && c.url.includes('/memberships/gym-a'), ); console.log('CALLS', JSON.stringify(calls.map((c) => c.init?.method + ' ' + c.url))); console.log('ERR', document.body.innerText); expect(del).toBeDefined(); }); });