Files
FitOS/app/test/ProfileOverview.test.tsx
tisachi fa89b91ed4 UI: klikalna karta statystyk na profilu i porzadki na tablicy silowni
Statystyki profilu w jednej klikalnej karcie (bez wiersza Statystyki w menu, etykieta Tonaz); na tablicy: Tablica nad Bytnoscia, tytul i nazwa silowni w jednym wierszu, usunete opisy sekcji; przyciski filtrow/sortowania pokazuja tylko stan (kategoria w aria-label); MonthPicker jako pigulka; akcje profilu w grupie Zarzadzaj.
2026-10-29 18:13:50 +01:00

294 lines
11 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { render, screen, within } 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';
// „Wczoraj" wg kalendarza lokalnego — wspólna podstawa mocków i oczekiwań,
// żeby toISOString() (UTC) nie rozmijało się z toLocaleDateString (lokalna)
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const YESTERDAY_ISO = `${yesterday.getFullYear()}-${String(yesterday.getMonth() + 1).padStart(2, '0')}-${String(
yesterday.getDate(),
).padStart(2, '0')}`;
const YESTERDAY_PL = yesterday.toLocaleDateString('pl-PL', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
});
const USER: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
birthDate: '1996-05-05T00:00:00.000Z',
heightCm: 180,
phone: '+48 600 000 000',
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() {
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 (url.includes('/me/body-parameters'))
return jsonResponse(200, {
weight: [{ id: 'w-1', value: 82.5, date: '2026-08-15T08:00:00.000Z' }],
circumferences: [],
});
if (url.includes('/me/history'))
return jsonResponse(200, {
sessions: [
{
// bieżąca data (wczoraj) — wchodzi w „Objętość 7 dni”
id: 's-1',
status: 'COMPLETED',
startedAt: new Date(Date.now() - 86400000).toISOString(),
endedAt: new Date(Date.now() - 86400000 + 3600000).toISOString(),
date: YESTERDAY_ISO,
dayOfWeek: 1,
plan: 'Plan A',
exercises: [
{
id: 'e-1',
name: 'Przysiady',
muscle: 'legs',
isExtra: false,
comments: [],
sets: [
{
index: 0,
reps: 10,
rir: 2,
difficulty: null,
planned: { reps: 10, loadKg: 60, restSec: 90, rir: null },
},
],
},
],
},
{
id: 's-2',
status: 'COMPLETED',
startedAt: '2026-08-22T16:00:00.000Z',
endedAt: '2026-08-22T17:00:00.000Z',
date: '2026-08-22',
dayOfWeek: 6,
plan: 'Plan A',
exercises: [],
},
{
id: 's-3',
status: 'ABANDONED',
startedAt: '2026-08-20T16:00:00.000Z',
endedAt: null,
date: '2026-08-20',
dayOfWeek: 4,
plan: 'Plan A',
exercises: [],
},
],
});
if (url.includes('/gyms'))
return jsonResponse(200, {
gyms: [
{
id: 'g-1',
name: 'Żelazna Świątynia',
location: 'Warszawa',
availability: null,
capacity: null,
equipment: [],
roles: ['MEMBER'],
},
],
});
if (url.includes('/me/stats'))
return jsonResponse(200, {
rangeDays: 90,
sessions: { count: 2, sets: 3, reps: 28, avgMinutes: 60 },
tonnageKg: 1100,
tonnageAllTimeKg: 43000,
topGym: { gymId: 'g-1', name: 'Żelazna Świątynia', sessions: 2 },
topEquipment: { equipmentId: 'eq-1', name: 'Sztanga', nameEn: null, sets: 2 },
topExercise: {
exerciseId: 'e-1',
name: 'Przysiady',
nameEn: null,
muscle: 'legs',
sessions: 1,
sets: 1,
},
muscles: [{ muscle: 'legs', sets: 1, volumeKg: 600 }],
weekday: [
{ dow: 0, sessions: 1 },
{ dow: 1, sessions: 0 },
{ dow: 2, sessions: 0 },
{ dow: 3, sessions: 0 },
{ dow: 4, sessions: 0 },
{ dow: 5, sessions: 1 },
{ dow: 6, sessions: 0 },
],
heatmap: [{ day: 0, hour: 18, count: 1 }],
weeklyTonnage: Array.from({ length: 12 }, (_, i) => ({
weekStart: new Date(Date.UTC(2026, 5, 29 + i * 7)).toISOString(),
volumeKg: 500 * (i + 1),
})),
records: [
{
exerciseId: 'e-1',
name: 'Przysiady',
nameEn: null,
muscle: 'legs',
oneRm: 80,
date: '2026-08-22T16:00:00.000Z',
},
],
plans: { completed: 1, abandoned: 0, daysCompleted: 3, daysSkipped: 1 },
});
if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
if (url.includes('/dashboard'))
return jsonResponse(200, {
killstreak: 3,
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' } });
}),
);
}
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: 'Mój profil' }));
expect(await screen.findByRole('heading', { name: 'Mój profil' })).toBeInTheDocument();
}
function renderApp() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/profile']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('Profile overview — hero, statystyki i wiersze sekcji', () => {
it('renders hero, mini-stats and section rows with summaries', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await loginToProfile(user);
// hero: nazwa + e-mail
expect(screen.getByText('Jan Kowalski')).toBeInTheDocument();
expect(screen.getByText('jan@test.local')).toBeInTheDocument();
// pasek statystyk: killstreak, objętość 7 dni (60×10 z wczorajszej sesji), sesje
// (bez „Ostatnia waga” i bez daty „ostatnia …” przy sesjach)
const killStat = screen.getByText('Killstreak').closest('div.min-w-0') as HTMLElement;
expect(within(killStat).getByText('3')).toBeInTheDocument();
expect(screen.queryByText('Ostatnia waga')).not.toBeInTheDocument();
expect(screen.getByText('Objętość 7 dni')).toBeInTheDocument();
expect(screen.getByText('600 kg')).toBeInTheDocument();
expect(screen.getByText('Sesje')).toBeInTheDocument();
// przy kafelku „Sesje” brak meta z datą (data ostatniej sesji zostaje w wierszu „Historia”)
const sesjeStat = screen.getByText('Sesje').closest('div.min-w-0') as HTMLElement;
expect(within(sesjeStat).queryByText(/ostatnia/)).not.toBeInTheDocument();
// statystyki w jednej karcie: przejście na podstronę jest w karcie, nie w liście sekcji
const statsLink = screen.getByRole('link', { name: 'Statystyki' });
expect(statsLink).toHaveAttribute('href', '/profile/stats');
// dane osobowe: imię i nazwisko + wiek/wzrost
const infoRow = await screen.findByRole('link', { name: /Dane osobowe/ });
expect(infoRow).toHaveTextContent('Jan Kowalski');
expect(infoRow).toHaveTextContent('30 lat · 180 cm');
// parametry ciała: najnowsza waga z datą
const bpRow = screen.getByRole('link', { name: /Parametry ciała/ });
expect(bpRow).toHaveTextContent('82.5 kg · 15.08.2026');
// historia: liczba sesji (polska odmiana) + data ostatniej (wczoraj)
const histRow = screen.getByRole('link', { name: /Historia treningów/ });
const lastDate = YESTERDAY_PL;
expect(histRow).toHaveTextContent(`3 sesje · ostatnia ${lastDate}`);
// siłownie: nazwy (sidebar ma też link „Siłownie" — wiersz niesie nazwę siłowni)
const gymsRow = screen.getByRole('link', { name: /^Siłownie / });
expect(gymsRow).toHaveTextContent('Żelazna Świątynia');
});
it('section rows navigate to the subpage and back', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await loginToProfile(user);
await user.click(await screen.findByRole('link', { name: /Historia treningów/ }));
// wspólna nazwa sekcji: topbar (h1) = PageHeader (h2)
expect(
await screen.findByRole('heading', { name: 'Historia treningów', level: 2 }),
).toBeInTheDocument();
// pełna sekcja na podstronie (nagłówek sesji: data · plan)
const lastDate = YESTERDAY_PL;
expect(screen.getByText(`${lastDate} · Plan A`)).toBeInTheDocument();
// wstecz wraca na przegląd („Wstecz” jest w topmenu i w treści — oba prowadzą do /profile)
await user.click(screen.getAllByRole('button', { name: 'Wstecz' })[0]);
expect(await screen.findByRole('heading', { name: 'Mój profil' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Dane osobowe/ })).toBeInTheDocument();
});
});