import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter, Route, Routes } from 'react-router-dom'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import UserDetail from '../src/pages/users/UserDetail'; import { setAccessToken } from '../src/api/client'; import { API_BASE } from '../src/config'; import type { Gym, User } from '../src/api/types'; const G1: Gym = { id: 'g1', name: 'Gym A', location: 'Warszawa', availability: null, capacity: 50, equipment: [], _count: { memberships: 1 }, }; const G2: Gym = { id: 'g2', name: 'Gym B', location: 'Kraków', availability: null, capacity: null, equipment: [], _count: { memberships: 0 }, }; const U1: User = { id: 'u1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski', age: 30, heightCm: 180, phone: null, isAdmin: false, availability: null, priorities: null, exclusions: null, developMuscles: ['chest'], canDoMuscles: [], difficultMuscles: [], avoidMuscles: ['legs'], createdAt: '2026-08-01T10:00:00.000Z', memberships: [{ gymId: 'g1', roles: ['OWNER', 'TRAINER'], gym: G1 }], }; const U2: User = { ...U1, id: 'u2', email: 'anna@test.local', firstName: 'Anna', lastName: 'Nowak', memberships: [{ gymId: 'g1', roles: ['MEMBER'], gym: G1 }], }; function jsonResponse(status: number, body: unknown) { return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' }, }); } function mockFetchSequence(...responses: Response[]) { const calls: { url: string; init?: RequestInit }[] = []; const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { calls.push({ url, init }); const next = responses.shift(); if (!next) throw new Error(`No more mocked responses for url: ${url}`); return next; }); vi.stubGlobal('fetch', fetchMock); return calls; } /** * Mockuje fetch wg URL (odporny na kolejność żądań). Zwraca listę wywołań. * `routes` mapuje fragment URL → fabryka odpowiedzi (wywoływana przy każdym żądaniu). */ function mockFetchRoutes(routes: Record unknown>) { const calls: { url: string; init?: RequestInit }[] = []; const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { calls.push({ url, init }); const handler = Object.entries(routes).find(([frag]) => url.includes(frag))?.[1]; if (!handler) throw new Error(`No mocked route for url: ${url}`); return jsonResponse(200, handler()); }); vi.stubGlobal('fetch', fetchMock); return calls; } function renderUserDetail(path = '/users/u1') { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); return render( } /> , ); } beforeEach(() => { setAccessToken('admin-tok'); }); afterEach(() => { vi.unstubAllGlobals(); }); describe('admin UserDetail page', () => { it('shows user details, per-role badges and role checkboxes', async () => { mockFetchSequence( jsonResponse(200, { users: [U1] }), jsonResponse(200, { gyms: [G1, G2] }), ); const user = userEvent.setup(); const { container } = renderUserDetail(); expect(await screen.findByRole('heading', { name: 'Jan Kowalski' })).toBeInTheDocument(); expect(screen.getByText('jan@test.local')).toBeInTheDocument(); // per-role summary badges in the header expect(screen.getByText('Właściciel: Gym A')).toBeInTheDocument(); expect(screen.getByText('Trener: Gym A')).toBeInTheDocument(); // membership row with the gym description expect(screen.getByText('Gym A')).toBeInTheDocument(); expect(screen.getByText('Warszawa')).toBeInTheDocument(); // searchable gym picker hides gyms the user already belongs to await user.click(screen.getByRole('combobox', { name: 'Szukaj siłowni' })); expect(screen.getByRole('option', { name: /Gym B/ })).toBeInTheDocument(); expect(screen.queryByRole('option', { name: /Gym A/ })).not.toBeInTheDocument(); // role checkboxes for the membership const ownerBox = screen.getByRole('checkbox', { name: 'Właściciel w Gym A' }); const trainerBox = screen.getByRole('checkbox', { name: 'Trener w Gym A' }); const memberBox = screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' }); expect(ownerBox).toBeChecked(); expect(trainerBox).toBeChecked(); expect(memberBox).not.toBeChecked(); // email is editable in the edit form const email = container.querySelector('input[type="email"]') as HTMLInputElement; expect(email).not.toBeNull(); expect(email.value).toBe('jan@test.local'); expect(screen.getByRole('button', { name: 'Zapisz' })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Usuń użytkownika' })).toBeInTheDocument(); }); it('checking a role checkbox sends a PATCH with the full roles list', async () => { const calls = mockFetchSequence( jsonResponse(200, { users: [U1] }), jsonResponse(200, { gyms: [G1, G2] }), jsonResponse(200, { membership: { gymId: 'g1', roles: ['OWNER', 'TRAINER', 'MEMBER'] } }), jsonResponse(200, { users: [U1] }), ); const user = userEvent.setup(); renderUserDetail(); await screen.findByRole('heading', { name: 'Jan Kowalski' }); await user.click(screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' })); const patch = calls.find( (c) => c.url === `${API_BASE}/admin/users/u1/memberships/g1` && c.init?.method === 'PATCH', ); expect(patch).toBeDefined(); expect(JSON.parse(patch?.init?.body as string)).toEqual({ roles: ['OWNER', 'TRAINER', 'MEMBER'], }); }); it('keeps the membership when the last role cannot be unchecked', async () => { const calls = mockFetchSequence( jsonResponse(200, { users: [U2] }), jsonResponse(200, { gyms: [G1, G2] }), ); const user = userEvent.setup(); renderUserDetail('/users/u2'); await screen.findByRole('heading', { name: 'Anna Nowak' }); // the only active role is locked: unchecking it would empty the membership const lastRole = screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' }); expect(lastRole).toBeDisabled(); expect(screen.getByRole('checkbox', { name: 'Trener w Gym A' })).toBeEnabled(); await user.click(lastRole); expect( calls.some((c) => c.init?.method === 'DELETE' || c.init?.method === 'PATCH'), ).toBe(false); }); it('adds a membership via the searchable gym picker', async () => { const calls = mockFetchSequence( jsonResponse(200, { users: [U1] }), jsonResponse(200, { gyms: [G1, G2] }), jsonResponse(201, { membership: { gymId: 'g2', roles: ['MEMBER'] } }), jsonResponse(200, { users: [U1] }), ); const user = userEvent.setup(); renderUserDetail(); await screen.findByRole('heading', { name: 'Jan Kowalski' }); const combobox = screen.getByRole('combobox', { name: 'Szukaj siłowni' }); await user.click(combobox); await user.type(combobox, 'Gym B'); await user.click(screen.getByRole('option', { name: /Gym B/ })); await user.click(screen.getByRole('button', { name: 'Dodaj członkostwo' })); const post = calls.find( (c) => c.url === `${API_BASE}/admin/users/u1/memberships` && c.init?.method === 'POST', ); expect(post).toBeDefined(); expect(JSON.parse(post?.init?.body as string)).toEqual({ gymId: 'g2', roles: ['MEMBER'] }); }); it('saves the training profile fields via the edit form', async () => { const focusAreas = [ { id: 'fa-1', name: 'Klatka piersiowa', muscle: 'chest', description: null, createdAt: '', updatedAt: '' }, { id: 'fa-2', name: 'Nogi', muscle: 'legs', description: null, createdAt: '', updatedAt: '' }, ]; const calls = mockFetchRoutes({ '/admin/users/u1/focus-chain': () => ({ develop: [], canDo: [], difficult: [], avoid: [] }), '/admin/focus-areas': () => ({ focusAreas }), '/admin/users': () => ({ users: [U1] }), '/admin/gyms': () => ({ gyms: [G1, G2] }), }); const user = userEvent.setup(); const { container } = renderUserDetail(); await screen.findByRole('heading', { name: 'Jan Kowalski' }); // availability editor renders a checkbox per day const wtCheckbox = await screen.findByRole('checkbox', { name: 'Wt: dostępny' }); expect(wtCheckbox).not.toBeNull(); // focus area chips are rendered from the catalog (per section) — wait for the async fetch const chestDevelop = await screen.findByRole('checkbox', { name: 'Klatka piersiowa (co rozwija)' }); const legsAvoid = await screen.findByRole('checkbox', { name: 'Nogi (co unikać)' }); expect(chestDevelop).toBeChecked(); // U1.developMuscles = ['chest'] expect(legsAvoid).toBeChecked(); // U1.avoidMuscles = ['legs'] // enable Tuesday (default 18:00-20:00) await user.click(wtCheckbox); // toggle off chest (develop) and toggle off legs (avoid) await user.click(chestDevelop); await user.click(legsAvoid); await user.click(screen.getByRole('button', { name: 'Zapisz' })); const patch = calls.find((c) => c.url === `${API_BASE}/admin/users/u1` && c.init?.method === 'PATCH'); expect(patch).toBeDefined(); const body = JSON.parse(patch?.init?.body as string); expect(body.availability).toEqual([null, { start: '18:00', end: '20:00' }, null, null, null, null, null]); // chest removed from develop, legs removed from avoid expect(body.developMuscles).toEqual([]); expect(body.canDoMuscles).toEqual([]); expect(body.difficultMuscles).toEqual([]); expect(body.avoidMuscles).toEqual([]); }); it('saves the edited email via the edit form', async () => { const calls = mockFetchSequence( jsonResponse(200, { users: [U1] }), jsonResponse(200, { gyms: [G1, G2] }), jsonResponse(200, { user: U1 }), jsonResponse(200, { users: [U1] }), ); const user = userEvent.setup(); const { container } = renderUserDetail(); await screen.findByRole('heading', { name: 'Jan Kowalski' }); const email = container.querySelector('input[type="email"]') as HTMLInputElement; await user.clear(email); await user.type(email, 'nowy-email@test.local'); await user.click(screen.getByRole('button', { name: 'Zapisz' })); const patch = calls.find( (c) => c.url === `${API_BASE}/admin/users/u1` && c.init?.method === 'PATCH', ); expect(patch).toBeDefined(); expect(JSON.parse(patch?.init?.body as string)).toMatchObject({ email: 'nowy-email@test.local', }); }); });