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 { useBodyParams } from '../src/store/body-params'; 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' }, }); } function mockApi( circ: { id: string; name: string; value: number; date: string }[] = [ { id: 'c-1', name: 'Biceps lewy', 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 byName = new Map(); for (const c of circState) { const entry = byName.get(c.name) ?? { name: c.name, points: [] }; entry.points.push({ id: c.id, value: c.value, date: c.date }); byName.set(c.name, entry); } return jsonResponse(200, { weight: weightState, circumferences: [...byName.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/ })); // tytuł podstrony jest tylko w topmenu (nagłówek Layout) expect(await screen.findByRole('heading', { name: 'Profil — parametry ciała' })).toBeInTheDocument(); } 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 }); // deterministyczny miesiąc — dane w mockach są z 07/08.2026 useBodyParams.setState({ month: '2026-08', availableMonths: [] }); }); 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); // lista wag (najnowsze pierwsze) i obwodów z przyciskami usuwania expect(await screen.findByText('82.5 kg')).toBeInTheDocument(); // 81.8 kg: nagłówek (ostatni pomiar) + wiersz listy expect(screen.getAllByText('81.8 kg').length).toBe(2); // 38 cm: nagłówek serii (ostatni pomiar) + wiersz listy expect(screen.getAllByText('38 cm').length).toBe(2); expect(screen.getAllByRole('button', { name: /Usuń pomiar wagi/ }).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 measurements by body part with a per-side legend', async () => { mockApi([ { id: 'c-1', name: 'Biceps lewy', value: 38, date: '2026-08-01T08:00:00.000Z' }, { id: 'c-2', name: 'Biceps lewy', value: 39, date: '2026-08-15T08:00:00.000Z' }, { id: 'c-3', name: 'Biceps prawy', value: 37, date: '2026-08-01T08:00:00.000Z' }, { id: 'c-4', name: 'Biceps prawy', value: 38, date: '2026-08-15T08:00:00.000Z' }, // starszy pomiar swobodnym tekstem z literówką — wykrywany jako Biceps { id: 'c-5', name: 'Bicepcs', value: 40, date: '2026-08-20T08:00:00.000Z' }, { id: 'c-6', name: 'Talia', value: 80, date: '2026-08-01T08:00:00.000Z' }, ]); const user = userEvent.setup(); renderApp(); await loginToProfile(user); // `Bicepcs` scalony z grupą Biceps — nie ma osobnego nagłówka expect(await screen.findByText('Biceps')).toBeInTheDocument(); // nagłówek grupy expect(screen.queryByText('Bicepcs')).not.toBeInTheDocument(); // nagłówek grupy: najnowszy pomiar (40 cm, 20.08) + wiersz listy expect(screen.getAllByText('40 cm').length).toBe(2); // legenda obu stron expect(screen.getByText('Lewy')).toBeInTheDocument(); expect(screen.getByText('Prawy')).toBeInTheDocument(); // wiersze listy z oznaczeniem strony expect(screen.getByText('15.08.2026 · Lewy')).toBeInTheDocument(); expect(screen.getByText('15.08.2026 · Prawy')).toBeInTheDocument(); // wiersz pomiaru bez strony (Bicepcs) — sama data expect(screen.getByText('20.08.2026')).toBeInTheDocument(); // talia to osobna grupa expect(screen.getByText('Talia')).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('filters data by the month selected in the top menu', async () => { mockApi([ { id: 'c-1', name: 'Talia', value: 80, date: '2026-07-10T08:00:00.000Z' }, { id: 'c-2', name: 'Talia', value: 82, date: '2026-08-10T08:00:00.000Z' }, ]); const user = userEvent.setup(); renderApp(); await loginToProfile(user); // domyślnie 08.2026 (ustawione w beforeEach): waga + talia z sierpnia expect(await screen.findByText('82.5 kg')).toBeInTheDocument(); expect(screen.getAllByText('82 cm').length).toBe(2); // nagłówek grupy + wiersz expect(screen.queryByText('10.07.2026')).not.toBeInTheDocument(); // selektor miesiąca jest w grupie lejka (ikona „Filtry” w nagłówku) await user.click(screen.getByRole('button', { name: 'Filtry' })); // strzałki: z sierpnia — poprzedni z danymi (lipiec) jest, kolejnego nie ma await waitFor(() => expect(screen.getByRole('button', { name: 'Poprzedni miesiąc z danymi' })).toBeEnabled(), ); expect(screen.getByRole('button', { name: 'Następny miesiąc z danymi' })).toBeDisabled(); // panel: filtr po roku + siatka 12 miesięcy; bez danych = nieaktywne await user.click(screen.getByRole('button', { name: 'Sierpień 2026' })); expect(screen.getByRole('button', { name: '2026', exact: true })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Lip', exact: true })).toBeInTheDocument(); expect(screen.getByRole('button', { name: 'Cze', exact: true })).toBeDisabled(); // zmiana miesiąca — dane z lipca, sierpień znika await user.click(screen.getByRole('button', { name: 'Lip', exact: true })); await waitFor(() => expect(screen.queryByText('82.5 kg')).not.toBeInTheDocument()); expect(screen.getAllByText('80 cm').length).toBe(2); expect(screen.queryByText('82 cm')).not.toBeInTheDocument(); // z lipca: poprzedniego z danymi nie ma, kolejny (sierpień) jest await waitFor(() => expect(screen.getByRole('button', { name: 'Następny miesiąc z danymi' })).toBeEnabled(), ); expect(screen.getByRole('button', { name: 'Poprzedni miesiąc z danymi' })).toBeDisabled(); }); it('pokaże deltę wagi w wybranym miesiącu i szybkie „+ Waga” w nagłówku karty', async () => { mockApi(); const user = userEvent.setup(); renderApp(); await loginToProfile(user); // delta: 81.8 (15.08) − 82.5 (01.08) = −0.7 kg (spadek) expect(await screen.findByText('82.5 kg')).toBeInTheDocument(); expect(screen.getByText('−0,7 kg w tym miesiącu')).toBeInTheDocument(); // szybkie dodanie wagi z nagłówka karty otwiera modal na zakładce Waga await user.click(screen.getByRole('button', { name: '+ Waga' })); expect(await screen.findByRole('dialog')).toBeInTheDocument(); expect(screen.getByPlaceholderText('waga (kg)')).toBeInTheDocument(); }); it('auto-selects the latest month with data when the selected month is empty', async () => { mockApi(); const user = userEvent.setup(); // wrzesień 2026 nie ma danych w mockach useBodyParams.setState({ month: '2026-09', availableMonths: [] }); renderApp(); await loginToProfile(user); // po załadowaniu danych: najnowszy miesiąc z danymi (sierpień) — selektor w grupie „Filtry” await user.click(screen.getByRole('button', { name: 'Filtry' })); expect(await screen.findByRole('button', { name: 'Sierpień 2026' })).toBeInTheDocument(); expect(screen.getByText('82.5 kg')).toBeInTheDocument(); }); });