import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MemoryRouter } from 'react-router-dom'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import App from '../src/App'; import { useAuth } from '../src/store/auth'; import { setAccessToken } from '../src/api/client'; import type { User } from '../src/api/types'; const USER: User = { id: 'u1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski', age: 30, heightCm: 180, phone: null, isAdmin: false, availability: null, priorities: 'chest', exclusions: 'knee', developMuscles: [], canDoMuscles: [], difficultMuscles: [], avoidMuscles: [], createdAt: '2026-08-22T10:00:00.000Z', }; function jsonResponse(status: number, body: unknown) { return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' }, }); } type CircRow = { id: string; typeId: string | null; side: 'left' | 'right' | null; name: string | null; value: number; date: string; }; function mockApi( circ: CircRow[] = [ { id: 'c-1', typeId: 'biceps', side: 'left', name: null, value: 38, date: '2026-08-01T08:00:00.000Z', }, ], ) { const weightState = [ { id: 'w-1', value: 82.5, date: '2026-08-01T08:00:00.000Z' }, { id: 'w-2', value: 81.8, date: '2026-08-15T08:00:00.000Z' }, ]; const circState = [...circ]; const deleted: { kind: 'weight' | 'circumference'; id: string }[] = []; vi.stubGlobal( 'fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input); const method = init?.method || 'GET'; if (url.includes('/auth/login')) return jsonResponse(200, { user: USER, accessToken: 'tok-1' }); if (url.includes('/auth/refresh')) return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } }); if (method === 'DELETE' && url.includes('/me/body-parameters/weight/')) { const id = url.split('/').pop()!; const idx = weightState.findIndex((w) => w.id === id); if (idx < 0) return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } }); weightState.splice(idx, 1); deleted.push({ kind: 'weight', id }); return new Response(null, { status: 204 }); } if (method === 'DELETE' && url.includes('/me/body-parameters/circumference/')) { const id = url.split('/').pop()!; const idx = circState.findIndex((c) => c.id === id); if (idx < 0) return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } }); circState.splice(idx, 1); deleted.push({ kind: 'circumference', id }); return new Response(null, { status: 204 }); } if (url.includes('/me/body-parameters')) { const byKey = new Map< string, { typeId: string | null; side: string | null; name: string | null; points: { id: string; value: number; date: string }[]; } >(); for (const c of circState) { const key = c.typeId ? `t:${c.typeId}:${c.side ?? ''}` : `n:${c.name ?? ''}`; const entry = byKey.get(key) ?? { typeId: c.typeId, side: c.typeId ? c.side : null, name: c.typeId ? null : c.name, points: [], }; entry.points.push({ id: c.id, value: c.value, date: c.date }); byKey.set(key, entry); } return jsonResponse(200, { weight: weightState, circumferences: [...byKey.values()] }); } if (url.includes('/me/history')) return jsonResponse(200, { sessions: [] }); if (url.includes('/me/focus-chain')) return jsonResponse(200, { priorities: [], exclusions: [] }); if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] }); if (url.includes('/focus-areas')) return jsonResponse(200, { focusAreas: [] }); if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] }); if (url.includes('/dashboard')) return jsonResponse(200, { killstreak: 0, activePlan: null, nextTraining: null, progress: null, }); if (url.includes('/exercises')) return jsonResponse(200, { exercises: [] }); if (url.includes('/plans')) return jsonResponse(200, { plans: [] }); if (url.includes('/calendar')) return jsonResponse(200, { month: '2026-08', days: [] }); return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } }); }), ); return { deleted }; } async function loginToProfile(user: userEvent.User) { expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument(); const email = document.querySelector('input[type="email"]') as HTMLInputElement; const password = document.querySelector('input[type="password"]') as HTMLInputElement; await user.type(email, 'jan@test.local'); await user.type(password, 'Password123!'); await user.click(screen.getByRole('button', { name: 'Zaloguj' })); expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument(); await user.click(screen.getByRole('link', { name: 'Profil' })); expect(await screen.findByRole('heading', { name: 'Profil' })).toBeInTheDocument(); // body parameters live on their own subpage — open it via the tile await user.click(await screen.findByRole('link', { name: /Parametry ciała/ })); // topbar (h1) = rodzic „Profil”, nazwa podstrony niżej jako PageHeader (h2) expect(await screen.findByRole('heading', { name: 'Profil', level: 1 })).toBeInTheDocument(); expect( await screen.findByRole('heading', { name: 'Parametry ciała', level: 2 }), ).toBeInTheDocument(); } /** Klik w zakładkę części ciała (sama nazwa — wartości są w panelu). */ function selectPart(part: string) { return screen.getByRole('button', { name: new RegExp(`^${part}$`) }); } function renderApp() { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } }, }); render( , ); } beforeEach(async () => { await new Promise((r) => setTimeout(r, 25)); setAccessToken(null); localStorage.clear(); useAuth.setState({ user: null, ready: false }); }); afterEach(() => { vi.unstubAllGlobals(); }); describe('Profile — body parameter removal', () => { it('lists measurements with a delete button', async () => { mockApi(); const user = userEvent.setup(); renderApp(); await loginToProfile(user); // domyślnie wybrana „Waga": pełna historia pomiarów z przyciskami usuwania expect(await screen.findByText('82.5 kg')).toBeInTheDocument(); // 81.8 kg: nagłówek panelu (ostatni pomiar) + wiersz listy expect(screen.getAllByText('81.8 kg').length).toBe(2); expect(screen.getAllByRole('button', { name: /Usuń pomiar wagi/ }).length).toBe(2); // obwody żyją w panelu swojej części — otwieranym z paska kaflów await user.click(selectPart('Biceps')); // 38 cm: nagłówek panelu (ostatni pomiar) + wiersz listy expect(screen.getAllByText('38 cm').length).toBe(2); expect(screen.getByRole('button', { name: /Usuń pomiar Biceps · Lewy/ })).toBeInTheDocument(); }); it('deletes a weight measurement after confirmation', async () => { const { deleted } = mockApi(); const user = userEvent.setup(); renderApp(); await loginToProfile(user); await screen.findByText('82.5 kg'); // usuwamy najnowszy pomiar (15.08.2026) await user.click(screen.getByRole('button', { name: /Usuń pomiar wagi z 15\.08\.2026/ })); // dialog potwierdzenia expect(await screen.findByRole('dialog')).toBeInTheDocument(); expect(screen.getByText('Usunąć pomiar?')).toBeInTheDocument(); await user.click(screen.getByRole('button', { name: 'Usuń' })); expect(await screen.findByText('Pomiar usunięty')).toBeInTheDocument(); await waitFor(() => expect(deleted).toEqual([{ kind: 'weight', id: 'w-2' }])); // po refetchu pomiar znika z listy await waitFor(() => expect(screen.queryByText('81.8 kg')).not.toBeInTheDocument()); }); it('groups sided series by type with a per-side legend', async () => { mockApi([ { id: 'c-1', typeId: 'biceps', side: 'left', name: null, value: 38, date: '2026-08-01T08:00:00.000Z', }, { id: 'c-2', typeId: 'biceps', side: 'left', name: null, value: 39, date: '2026-08-15T08:00:00.000Z', }, { id: 'c-3', typeId: 'biceps', side: 'right', name: null, value: 37, date: '2026-08-01T08:00:00.000Z', }, { id: 'c-4', typeId: 'biceps', side: 'right', name: null, value: 38, date: '2026-08-15T08:00:00.000Z', }, // starszy pomiar swobodnym tekstem — zachowany jako własna grupa (bez rozpoznawania co do typu) { id: 'c-5', typeId: null, side: null, name: 'Bicepcs', value: 40, date: '2026-08-20T08:00:00.000Z', }, { id: 'c-6', typeId: 'waist', side: null, name: null, value: 80, date: '2026-08-01T08:00:00.000Z', }, ]); const user = userEvent.setup(); renderApp(); await loginToProfile(user); // Biceps = jedna grupa (typ), strony osobno await user.click(selectPart('Biceps')); expect(screen.getByRole('heading', { name: 'Biceps — lewy', level: 3 })).toBeInTheDocument(); expect(screen.getByRole('heading', { name: 'Biceps — prawy', level: 3 })).toBeInTheDocument(); // wiersze listy z oznaczeniem strony expect(screen.getByText('15.08.2026 · Lewy')).toBeInTheDocument(); expect(screen.getByText('15.08.2026 · Prawy')).toBeInTheDocument(); // swobodna nazwa to osobna grupa, zachowana dosłownie await user.click(selectPart('Bicepcs')); expect(screen.getAllByText('40 cm').length).toBe(2); // talia to osobna grupa — własny kafel i panel await user.click(selectPart('Talia')); expect(screen.getAllByText('80 cm').length).toBe(2); // nagłówek panelu + wiersz }); it('rozbija strony na osobne wykresy (lewy pierwszy), bez podwójnych dat na osi', async () => { mockApi([ // dwa prawe i jedno lewe z TEJ SAMEJ daty — strony rysowane osobno, // dni łączone w pojedyncze kategorie osi (bez dublujących się etykiet) { id: 'c-1', typeId: 'thigh', side: 'right', name: null, value: 55, date: '2026-08-10T08:00:00.000Z', }, { id: 'c-2', typeId: 'thigh', side: 'right', name: null, value: 56, date: '2026-08-12T19:00:00.000Z', }, { id: 'c-3', typeId: 'thigh', side: 'left', name: null, value: 54, date: '2026-08-10T12:00:00.000Z', }, ]); const user = userEvent.setup(); renderApp(); await loginToProfile(user); await user.click(selectPart('Udo')); // nagłówek sekcji strony (ostatni 56) + wiersz listy expect((await screen.findAllByText('56 cm')).length).toBeGreaterThanOrEqual(2); // dwa niezależne divy: „Udo — lewe” zawsze przed „Udo — prawe” const lewy = screen.getByRole('heading', { name: 'Udo — lewe', level: 3 }); const prawy = screen.getByRole('heading', { name: 'Udo — prawe', level: 3 }); expect(lewy.compareDocumentPosition(prawy) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); // strona z jednym pomiarem uczciwie sygnalizuje za mało danych expect(screen.getByText(/Za mało danych na wykres/)).toBeInTheDocument(); }); it('opens the add-measurement modal from the context menu', async () => { mockApi(); const user = userEvent.setup(); renderApp(); await loginToProfile(user); // formularze nie są inline — otwiera je przycisk w menu kontekstowym (za ikoną ➕) expect(screen.queryByPlaceholderText('waga (kg)')).not.toBeInTheDocument(); await user.click(screen.getByRole('button', { name: 'Dodawanie' })); await user.click(screen.getByRole('button', { name: 'Dodaj pomiar' })); expect(await screen.findByRole('dialog')).toBeInTheDocument(); // zakładka Waga: wartość + data (pusta = dziś) expect(screen.getByPlaceholderText('waga (kg)')).toBeInTheDocument(); expect(screen.getByLabelText('Data wagi')).toBeInTheDocument(); // zakładka Obwód: lista typów + wartość await user.click(screen.getByRole('button', { name: 'Obwód' })); expect(screen.getByRole('option', { name: 'Talia' })).toBeInTheDocument(); expect(screen.getByPlaceholderText('wartość (cm)')).toBeInTheDocument(); }); it('shows the weight delta vs previous measurement; adding lives only in the top menu', async () => { mockApi(); const user = userEvent.setup(); renderApp(); await loginToProfile(user); // postęp: 81.8 (15.08) − 82.5 (01.08) = −0,7 kg (spadek) — liczony z pełnej historii expect(await screen.findByText('82.5 kg')).toBeInTheDocument(); expect(screen.getByText('−0,7 kg od pierwszego')).toBeInTheDocument(); // 1 kontrolka = 1 miejsce: w treści brak przycisków dodawania — dodaje się z topmenu expect(screen.queryByRole('button', { name: /Dodaj wagę/ })).not.toBeInTheDocument(); await user.click(screen.getByRole('button', { name: 'Dodaj pomiar' })); expect(await screen.findByRole('dialog')).toBeInTheDocument(); expect(screen.getByPlaceholderText('waga (kg)')).toBeInTheDocument(); }); it('shows all measurements from every month (chart covers the full history)', async () => { mockApi([ { id: 'c-1', typeId: 'waist', side: null, name: null, value: 80, date: '2026-07-10T08:00:00.000Z', }, { id: 'c-2', typeId: 'waist', side: null, name: null, value: 82, date: '2026-08-10T08:00:00.000Z', }, ]); const user = userEvent.setup(); renderApp(); await loginToProfile(user); // pomiary spoza bieżącego miesiąca są widoczne bez żadnego filtra expect(await screen.findByText('82.5 kg')).toBeInTheDocument(); await user.click(selectPart('Talia')); expect(screen.getByText('10.07.2026')).toBeInTheDocument(); // 10.08 w nagłówku panelu i w wierszu listy (zakładka pokazuje samą wartość) expect(screen.getAllByText('10.08.2026').length).toBe(2); // postęp Talii: 82 (10.08) − 80 (10.07) = +2 cm expect(screen.getByText('+2 cm od pierwszego')).toBeInTheDocument(); }); });