Profil: GET /me/stats (ulubiona silownia/sprzet/cwiczenie, partie ciala, heatma, tonaz 12 tyg., rekordy Epley top5) + widok /profile/stats i podsumowanie na przegladzie. Tablica: GET /gyms/:id/board + PATCH /gyms/:id/stats-consent (GymMembership.statsOptIn, migracja gym_membership_stats_opt_in) — anonimowe agregaty, ranking i rekordy 1RM z atrybucja nicka tylko po zgodzie; /gyms/:id/board + pelnoekranowy tryb TV /gyms/:id/board/tv (TvShell, auto-refetch co 5 min); kafelek na GymDetail. Wspolne: api lib/strengthStats (Epley/efektywne obciazenie), app lib/stats-equiv + components/stats (MuscleSplit, WeeklyTonnageChart), storey stats-range/board-range. Testy: api 322 unit + 12 integracji (board, me-stats); app 285 unit; e2e gym-board 4, profile-stats 3.
228 lines
8.5 KiB
TypeScript
228 lines
8.5 KiB
TypeScript
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';
|
|
|
|
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' },
|
|
});
|
|
}
|
|
|
|
const weekly = Array.from({ length: 12 }, (_, i) => ({
|
|
weekStart: new Date(Date.UTC(2026, 5, 29 + i * 7)).toISOString(),
|
|
volumeKg: 500 * (i + 1),
|
|
}));
|
|
|
|
function statsBody(range: string) {
|
|
const all = range === 'all';
|
|
return {
|
|
rangeDays: all ? null : Number(range),
|
|
sessions: { count: all ? 6 : 2, sets: all ? 20 : 6, reps: all ? 180 : 52, avgMinutes: 70 },
|
|
tonnageKg: all ? 9400 : 3200,
|
|
tonnageAllTimeKg: 9400,
|
|
topGym: { gymId: 'g-1', name: 'Żelazna Świątynia', sessions: all ? 6 : 2 },
|
|
topEquipment: all
|
|
? { equipmentId: 'eq-2', name: 'Hantle', nameEn: null, sets: 9 }
|
|
: { equipmentId: 'eq-1', name: 'Sztanga', nameEn: null, sets: 4 },
|
|
topExercise: {
|
|
exerciseId: 'e-1',
|
|
name: 'Przysiady',
|
|
nameEn: null,
|
|
muscle: 'legs',
|
|
sessions: all ? 4 : 2,
|
|
sets: all ? 12 : 6,
|
|
},
|
|
muscles: [
|
|
{ muscle: 'legs', sets: all ? 12 : 4, volumeKg: all ? 5200 : 2000 },
|
|
{ muscle: 'chest', sets: all ? 8 : 2, volumeKg: all ? 4200 : 1200 },
|
|
],
|
|
weekday: [
|
|
{ dow: 0, sessions: all ? 3 : 1 },
|
|
{ dow: 1, sessions: 0 },
|
|
{ dow: 2, sessions: all ? 2 : 1 },
|
|
{ dow: 3, sessions: 0 },
|
|
{ dow: 4, sessions: 0 },
|
|
{ dow: 5, sessions: 0 },
|
|
{ dow: 6, sessions: all ? 1 : 0 },
|
|
],
|
|
heatmap: [
|
|
{ day: 0, hour: 18, count: all ? 3 : 1 },
|
|
{ day: 2, hour: 7, count: all ? 2 : 1 },
|
|
],
|
|
weeklyTonnage: weekly,
|
|
records: [
|
|
{
|
|
exerciseId: 'e-1',
|
|
name: 'Przysiady',
|
|
nameEn: null,
|
|
muscle: 'legs',
|
|
oneRm: 116.7,
|
|
date: '2026-08-24T16:00:00.000Z',
|
|
},
|
|
{
|
|
exerciseId: 'e-2',
|
|
name: 'Wyciskanie',
|
|
nameEn: null,
|
|
muscle: 'chest',
|
|
oneRm: 80.6,
|
|
date: '2026-08-21T16:00:00.000Z',
|
|
},
|
|
],
|
|
plans: { completed: 2, abandoned: 1, daysCompleted: 12, daysSkipped: 3 },
|
|
};
|
|
}
|
|
|
|
function mockApi() {
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = String(input);
|
|
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' } });
|
|
const statsRange = url.match(/\/me\/stats\?range=([^&]+)/)?.[1];
|
|
if (statsRange) return jsonResponse(200, statsBody(statsRange));
|
|
if (url.includes('/me/stats')) return jsonResponse(200, statsBody('90'));
|
|
if (url.includes('/me/body-parameters'))
|
|
return jsonResponse(200, { weight: [], circumferences: [] });
|
|
if (url.includes('/me/history')) return jsonResponse(200, { sessions: [] });
|
|
if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] });
|
|
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,
|
|
});
|
|
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
|
|
}),
|
|
);
|
|
}
|
|
|
|
function renderApp() {
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
|
});
|
|
render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<MemoryRouter initialEntries={['/profile']}>
|
|
<App />
|
|
</MemoryRouter>
|
|
</QueryClientProvider>,
|
|
);
|
|
}
|
|
|
|
async function gotoStats(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' }));
|
|
await user.click(await screen.findByRole('link', { name: 'Mój profil' }));
|
|
await user.click(await screen.findByRole('link', { name: /^Statystyki/ }));
|
|
expect(await screen.findByRole('heading', { name: 'Statystyki', level: 2 })).toBeInTheDocument();
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
await new Promise((r) => setTimeout(r, 25));
|
|
setAccessToken(null);
|
|
localStorage.clear();
|
|
useAuth.setState({ user: null, ready: false });
|
|
// zakres store jest modułem współdzielonym — zawsze startuj od domyślnego 90
|
|
const { useStatsRange } = await import('../src/store/stats-range');
|
|
useStatsRange.setState({ range: '90' });
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
describe('Profile stats — podstrona Statystyki', () => {
|
|
it('navigates from profile preview and shows favorites, muscles and records', async () => {
|
|
mockApi();
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
// wiersz sekcji na przeglądzie prowadzi do /profile/stats
|
|
await gotoStats(user);
|
|
|
|
// ulubione (karta „Twoje ulubione”): siłownia, sprzęt, ćwiczenie
|
|
const favorites = screen.getByText('Twoje ulubione').closest('[data-slot="card"]') as HTMLElement;
|
|
expect(within(favorites).getByText('Ulubiona siłownia')).toBeInTheDocument();
|
|
expect(within(favorites).getByText('Żelazna Świątynia')).toBeInTheDocument();
|
|
expect(within(favorites).getByText('Ulubiony sprzęt')).toBeInTheDocument();
|
|
expect(within(favorites).getByText('Sztanga')).toBeInTheDocument();
|
|
expect(within(favorites).getByText('Ulubione ćwiczenie')).toBeInTheDocument();
|
|
expect(within(favorites).getByText('Przysiady')).toBeInTheDocument();
|
|
|
|
// KPI w zakresie 90 dni: sesje 2, serie 6, powtórzenia 52, tonaż 3,2 t
|
|
const sessionsKpi = screen.getByText('Sesje').closest('[data-slot="card"]') as HTMLElement;
|
|
expect(within(sessionsKpi).getByText('2')).toBeInTheDocument();
|
|
const setsKpi = screen.getByText('Serie').closest('[data-slot="card"]') as HTMLElement;
|
|
expect(within(setsKpi).getByText('6')).toBeInTheDocument();
|
|
const repsKpi = screen.getByText('Powtórzenia').closest('[data-slot="card"]') as HTMLElement;
|
|
expect(within(repsKpi).getByText('52')).toBeInTheDocument();
|
|
expect(screen.getByText('3,2 t')).toBeInTheDocument();
|
|
|
|
// partie ciała: 4 serie nogi · 2 t + badge klatka
|
|
expect(screen.getByText('Co trenujesz najczęściej')).toBeInTheDocument();
|
|
expect(screen.getByText('4 serii · 2 t')).toBeInTheDocument();
|
|
|
|
// rekordy 1RM (Epley): wartość i jednostka
|
|
expect(screen.getByText('Rekordy 1RM')).toBeInTheDocument();
|
|
expect(screen.getByText('116,7 kg')).toBeInTheDocument();
|
|
|
|
// heatma + ekwiwalenty + konsekwencja
|
|
expect(screen.getByText('Kiedy ćwiczysz')).toBeInTheDocument();
|
|
expect(screen.getByText('Przeniesione tony')).toBeInTheDocument();
|
|
expect(screen.getByText('Konsekwencja i plany')).toBeInTheDocument();
|
|
expect(screen.getByText('słoń afrykański (6 t)')).toBeInTheDocument();
|
|
});
|
|
|
|
it('range Select in the topbar refetches stats', async () => {
|
|
mockApi();
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await gotoStats(user);
|
|
|
|
const select = screen.getByRole('combobox', { name: 'Zakres statystyk' });
|
|
expect(select).toHaveValue('90');
|
|
await user.selectOptions(select, 'all');
|
|
|
|
// dla „Wszystko” mock oddaje inny ulubiony sprzęt i więcej sesji
|
|
const favorites = screen
|
|
.getByText('Twoje ulubione')
|
|
.closest('[data-slot="card"]') as HTMLElement;
|
|
expect(await within(favorites).findByText('Hantle')).toBeInTheDocument();
|
|
expect(within(favorites).getByText('6 sesji')).toBeInTheDocument();
|
|
});
|
|
});
|