import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'; 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 GymDetail from '../src/pages/gyms/GymDetail'; import { setAccessToken } from '../src/api/client'; import { useTopbarStore } from '../src/topbar/store'; import { Topbar } from '../src/topbar'; import type { Equipment, Gym, User } from '../src/api/types'; const OWNER1 = { id: 'u-owner', firstName: 'Anna', lastName: 'Kowalska', email: 'anna@fitos.pl' }; const G1: Gym = { id: 'g1', name: 'Gym A', location: 'Polna 4, 00-001 Warszawa', addressLine1: 'Polna 4', addressLine2: null, postalCode: '00-001', city: 'Warszawa', countryCode: 'PL', availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null], capacity: 50, kind: 'REAL', isPrivate: false, equipment: [], coverPhoto: null, _count: { memberships: 12 }, owners: [OWNER1], }; const EQ1: Equipment = { id: 'eq-1', name: 'sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: null, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', }; const EQ2: Equipment = { id: 'eq-2', name: 'hantle', kind: 'DUMBBELL', spec: { minKg: 2.5, maxKg: 25 }, description: null, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', }; const G1_EQ: Gym = { ...G1, equipment: [{ id: 'ge-2', gymId: 'g1', equipmentId: 'eq-2', quantity: 2, equipment: EQ2 }], }; const U1 = { id: 'u1', email: 'jan@fitos.pl', firstName: 'Jan', lastName: 'Kowalski', nickname: null, isAdmin: false, } as unknown as User; type Call = { url: string; method?: string; body?: unknown }; function jsonResponse(status: number, body: unknown) { return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' }, }); } /** Wspólny mock: karta siłowni, katalog, wyjątki, użytkownicy i endpointy właścicieli. */ function stubGymFetch(options: { gym?: Gym; calls?: Call[] } = {}) { const gym = options.gym ?? G1; const calls = options.calls ?? []; const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input); const method = init?.method ?? 'GET'; calls.push({ url, method, body: init?.body ? JSON.parse(String(init.body)) : undefined }); if (url.includes('/admin/equipment')) return jsonResponse(200, { equipment: [EQ1, EQ2] }); if (url.includes('/exceptions')) return jsonResponse(200, { exceptions: [] }); if (url.includes('/admin/users')) return jsonResponse(200, { users: [U1] }); if (url.endsWith('/admin/gyms/g1/equipment') && method === 'POST') { return jsonResponse(200, { gym: G1_EQ, instance: { id: 'ge-9', gymId: 'g1', equipmentId: 'eq-2', quantity: 1, spec: null }, }); } if (url.includes('/admin/gyms/g1/equipment/ge-2') && method === 'PATCH') { return jsonResponse(200, { gym: G1_EQ }); } if (url.includes('/admin/gyms/g1/owners') && method === 'POST') { return jsonResponse(200, { membership: { gymId: 'g1', roles: ['OWNER'] } }); } if (url.includes('/admin/gyms/g1/owners') && method === 'DELETE') return jsonResponse(204, {}); if (url.includes('/admin/gyms/g1')) return jsonResponse(200, gym); throw new Error(`Unexpected fetch: ${method} ${url}`); }); vi.stubGlobal('fetch', fetchMock); return calls; } /** Akcja grupowa w topbarze (ikona grupy ma ten sam label — wybieramy po data-slot Buttona). */ function actionButton(label: string): HTMLElement { const btn = Array.from(document.querySelectorAll('button[data-slot="button"]')).find( (b) => b.textContent?.trim() === label, ); if (!btn) throw new Error(`Brak akcji w menu: ${label}`); return btn; } function renderGymDetail() { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); return render( } /> , ); } beforeEach(() => { setAccessToken('admin-tok'); }); afterEach(() => { vi.unstubAllGlobals(); }); describe('admin GymDetail page', () => { it('shows read-only details, owners and top-menu groups (app parity)', async () => { stubGymFetch(); renderGymDetail(); expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); // hero pokazuje location (string derivowany), karta Dane pokazuje adres strukturalny expect(screen.getByText('Polna 4, 00-001 Warszawa')).toBeInTheDocument(); expect(screen.getByText('Polna 4', { exact: true })).toBeInTheDocument(); expect(screen.getByText('00-001 Warszawa')).toBeInTheDocument(); expect(screen.getByText('12 członków')).toBeInTheDocument(); expect(screen.getByText('Anna Kowalska')).toBeInTheDocument(); // menu kontekstowe: grupy Edycja/Galeria/Urządzenia + admin-only Właściciele + Ogłoszenia const config = useTopbarStore.getState().config; expect(config?.groups?.map((g) => g.id)).toEqual([ 'edit', 'gallery', 'equipment', 'owners', 'announcements', ]); expect(config?.actions?.some((a) => a.label === 'Usuń siłownię')).toBe(true); }); it('manages equipment in a modal opened from the „Urządzenia” group', async () => { const calls = stubGymFetch({ gym: G1_EQ }); renderGymDetail(); expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); fireEvent.click(actionButton('Urządzenia')); const dialog = await screen.findByRole('dialog'); // select pokazuje cały katalog — sprzęt już dodany jest oznaczony bieżącą ilością expect( await within(dialog).findByRole('option', { name: 'hantle (na stanie: 2)' }), ).toBeInTheDocument(); fireEvent.change(within(dialog).getByRole('combobox', { name: 'Dodaj urządzenie' }), { target: { value: 'eq-2' }, }); // pozycja z katalogu DUMBBELL wymaga własnych parametrów — zawsze wpisywanych przez admina fireEvent.change(within(dialog).getByRole('spinbutton', { name: 'Min. obciążenie (kg)' }), { target: { value: '2.5' }, }); fireEvent.change(within(dialog).getByRole('spinbutton', { name: 'Max. obciążenie (kg)' }), { target: { value: '25' }, }); fireEvent.click(within(dialog).getByRole('button', { name: 'Dodaj', exact: true })); // każde dodanie = POST tworzący NOWĄ instancję (bez PATCH-a ilości istniejącej) await waitFor(() => expect( calls.find((c) => c.method === 'POST' && c.url.endsWith('/admin/gyms/g1/equipment')), ).toBeTruthy(), ); expect( calls.find((c) => c.method === 'POST' && c.url.endsWith('/admin/gyms/g1/equipment'))?.body, ).toEqual({ equipmentId: 'eq-2', quantity: 1, spec: { minKg: 2.5, maxKg: 25 } }); expect(calls.some((c) => c.method === 'PATCH')).toBe(false); }); it('grants and revokes gym owners via admin-only owner endpoints', async () => { const calls = stubGymFetch(); renderGymDetail(); expect(await screen.findByRole('heading', { name: 'Gym A' })).toBeInTheDocument(); fireEvent.click(actionButton('Właściciele')); const dialog = await screen.findByRole('dialog'); expect(within(dialog).getByText('Anna Kowalska')).toBeInTheDocument(); // odebranie roli = DELETE /admin/gyms/:id/owners/:userId fireEvent.click(within(dialog).getByRole('button', { name: 'Odbierz rolę' })); await waitFor(() => expect( calls.find((c) => c.method === 'DELETE' && c.url.endsWith('/owners/u-owner')), ).toBeTruthy(), ); // nadanie roli = POST /admin/gyms/:id/owners { userId } const picker = within(dialog).getByRole('combobox', { name: 'Szukaj przyszłego właściciela' }); fireEvent.change(picker, { target: { value: 'jan' } }); fireEvent.click(await within(dialog).findByRole('option', { name: /Jan Kowalski/ })); fireEvent.click(within(dialog).getByRole('button', { name: 'Nadaj właściciela' })); await waitFor(() => expect(calls.find((c) => c.method === 'POST' && c.url.endsWith('/owners'))).toBeTruthy(), ); expect(calls.find((c) => c.method === 'POST' && c.url.endsWith('/owners'))?.body).toEqual({ userId: 'u1', }); }); });