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 UserMemberships from '../src/pages/users/UserMemberships'; 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', nickname: null, socialMedia: null, age: 30, heightCm: 180, phone: null, isAdmin: false, availability: null, priorities: null, exclusions: null, developMuscles: [], canDoMuscles: [], difficultMuscles: [], avoidMuscles: [], 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; } function renderMemberships(path: string) { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); return render( } /> , ); } beforeEach(() => { setAccessToken('admin-tok'); }); afterEach(() => { vi.unstubAllGlobals(); }); describe('admin UserMemberships page', () => { it('shows memberships with role checkboxes and hides joined gyms in the picker', async () => { mockFetchSequence( jsonResponse(200, { users: [U1] }), jsonResponse(200, { gyms: [G1, G2] }), ); const user = userEvent.setup(); renderMemberships('/users/u1/memberships'); expect( await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' }), ).toBeInTheDocument(); expect(screen.getByText('Gym A')).toBeInTheDocument(); expect(screen.getByText('Warszawa')).toBeInTheDocument(); // wyszukiwarka siłowni ukrywa siłownie, do których user już należy 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(); // checkboxy ról członkostwa expect(screen.getByRole('checkbox', { name: 'Właściciel w Gym A' })).toBeChecked(); expect(screen.getByRole('checkbox', { name: 'Trener w Gym A' })).toBeChecked(); expect(screen.getByRole('checkbox', { name: 'Ćwiczący w Gym A' })).not.toBeChecked(); }); 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(); renderMemberships('/users/u1/memberships'); await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' }); 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(); renderMemberships('/users/u2/memberships'); await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' }); // jedyna aktywna rola jest zablokowana — odznaczenie zostawiłoby puste członkostwo 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(); renderMemberships('/users/u1/memberships'); await screen.findByRole('heading', { name: 'Członkostwa w siłowniach' }); 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'] }); }); });