Files
FitOS/app/test/GymBoard.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

305 lines
10 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 { GymBoardData, User } from '../src/api/types';
const USER: User = {
id: 'user-test',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
nickname: null,
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 boardBody(optIn: boolean, rangeDays: number): GymBoardData {
const body: GymBoardData = {
gym: { id: 'gym-1', name: 'Żelazna Świątynia' },
myStatsOptIn: optIn,
rangeDays,
ranking: [
{
userId: 'u-ala',
nickname: 'żelazka',
firstName: 'Ala',
lastName: 'Nowak',
sessions: 8,
tonnageKg: 18200,
days: 6,
},
{
userId: 'u-bob',
nickname: null,
firstName: 'Bob',
lastName: 'Kowal',
sessions: 5,
tonnageKg: 11000,
days: 4,
},
],
aggregate: {
tonnageKg: 42000,
sessions: 24,
uniqueExercisers: 9,
muscles: [
{ muscle: 'legs', sets: 40, volumeKg: 21000 },
{ muscle: 'chest', sets: 25, volumeKg: 9500 },
],
},
records: [
{
exerciseId: 'e-squat',
name: 'Przysiady',
nameEn: 'Squat',
muscle: 'legs',
oneRm: 140,
date: '2026-09-12T16:00:00.000Z',
author: { nickname: 'żelazka', firstName: 'Ala', lastName: 'Nowak' },
},
{
exerciseId: 'e-bench',
name: 'Wyciskanie leżąc',
nameEn: 'Bench press',
muscle: 'chest',
oneRm: 100,
date: '2026-08-30T16:00:00.000Z',
author: null,
},
],
};
if (optIn) {
body.ranking.push({
userId: USER.id,
nickname: null,
firstName: USER.firstName,
lastName: USER.lastName,
sessions: 3,
tonnageKg: 5200,
days: 3,
});
body.records[1].author = {
nickname: null,
firstName: USER.firstName,
lastName: USER.lastName,
};
}
return body;
}
// stan zgody przełączany PATCH-em (identyczny flow jak w mock-api e2e)
let boardOptIn = false;
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' } });
if (url.includes('/stats-consent')) {
const payload = JSON.parse(String(init?.body ?? '{}')) as { enabled?: boolean };
boardOptIn = Boolean(payload.enabled);
return jsonResponse(200, { statsOptIn: boardOptIn });
}
const boardRange = url.match(/\/gyms\/[^/]+\/board\?range=([^&]+)/)?.[1];
if (boardRange) return jsonResponse(200, boardBody(boardOptIn, Number(boardRange)));
if (url.includes('/gyms/gym-1'))
return jsonResponse(200, {
gym: {
id: 'gym-1',
name: 'Żelazna Świątynia',
kind: 'REAL',
location: 'Warszawa',
capacity: 50,
isPrivate: false,
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
equipment: [],
photos: [],
coverPhoto: null,
currentOccupancy: null,
},
roles: ['MEMBER'],
isAdmin: false,
});
if (url.includes('/gyms'))
return jsonResponse(200, {
gyms: [
{
id: 'gym-1',
name: 'Żelazna Świątynia',
kind: 'REAL',
location: 'Warszawa',
capacity: 50,
isPrivate: false,
roles: ['MEMBER'],
equipment: [],
coverPhoto: null,
currentOccupancy: null,
},
],
});
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 gotoBoard(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: 'Siłownie' }));
await user.click(await screen.findByRole('link', { name: 'Żelazna Świątynia' }));
await user.click(await screen.findByRole('link', { name: /^Tablica/ }));
expect(await screen.findByRole('heading', { name: 'Tablica', level: 2 })).toBeInTheDocument();
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
boardOptIn = false;
useAuth.setState({ user: null, ready: false });
// zakres store jest modułem współdzielonym — zawsze startuj od domyślnego 30
const { useBoardRange } = await import('../src/store/board-range');
useBoardRange.setState({ range: '30' });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('Gym board — podstrona Tablica', () => {
it('shows ranking, anonymous aggregates with equivalents and records with anonymous author', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await gotoBoard(user);
// ranking: nick członka z zgodą + nazwa bez nicka + liczba sesji
const ranking = screen
.getByText('Ranking treningów')
.closest('[data-slot="card"]') as HTMLElement;
expect(within(ranking).getByText('żelazka')).toBeInTheDocument();
expect(within(ranking).getByText('Bob Kowal')).toBeInTheDocument();
expect(within(ranking).getByText('8 sesji')).toBeInTheDocument();
// bez opt-in: własny wiersz rankingu niedostępny
expect(within(ranking).queryByText('Jan Kowalski')).not.toBeInTheDocument();
// zbiorowość: tonaż 42 t + ekwiwalenty (etykiety jednostek + licznik „× N")
const aggregate = screen
.getByText('Zbiorowość siłowni')
.closest('[data-slot="card"]') as HTMLElement;
expect(within(aggregate).getByText('42 t')).toBeInTheDocument();
expect(within(aggregate).getByText('słoń afrykański (6 t)')).toBeInTheDocument();
expect(within(aggregate).getByText('samochód osobowy (1,5 t)')).toBeInTheDocument();
// partie ciała (współdzielony MuscleSplit): serie + tonaż
const muscles = screen
.getByText('Partie ciała siłowni')
.closest('[data-slot="card"]') as HTMLElement;
expect(within(muscles).getByText('40 serii · 21 t')).toBeInTheDocument();
// rekordy: autor z opt-in po nicku, reszta anonimowo
const records = screen.getByText('Rekordy 1RM').closest('[data-slot="card"]') as HTMLElement;
expect(within(records).getByText('140 kg')).toBeInTheDocument();
expect(within(records).getByText(/anonim/)).toBeInTheDocument();
});
it('consent switch in the topbar opts in via PATCH and reveals own row and author', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await gotoBoard(user);
const toggle = screen.getByRole('switch', { name: 'Pokaż nick na tablicy' });
expect(toggle).toHaveAttribute('aria-checked', 'false');
expect(screen.getByText('Nick ukryty')).toBeInTheDocument();
await user.click(toggle);
const ranking = screen
.getByText('Ranking treningów')
.closest('[data-slot="card"]') as HTMLElement;
expect(await within(ranking).findByText('Jan Kowalski')).toBeInTheDocument();
expect(await screen.findByText('Nick widoczny')).toBeInTheDocument();
const records = screen.getByText('Rekordy 1RM').closest('[data-slot="card"]') as HTMLElement;
expect(within(records).getByText(/Jan Kowalski/)).toBeInTheDocument();
});
it('range Select in the topbar refetches the board', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await gotoBoard(user);
const select = screen.getByRole('combobox', { name: 'Zakres tablicy' });
expect(select).toHaveValue('30');
await user.selectOptions(select, '7');
expect(select).toHaveValue('7');
});
it('TV mode renders fullscreen board without topbar controls', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await gotoBoard(user);
await user.click(screen.getByRole('button', { name: 'Tryb TV' }));
expect(
await screen.findByRole('heading', { name: 'Żelazna Świątynia', level: 1 }),
).toBeInTheDocument();
expect(screen.getByText('Odświeżane co 5 minut')).toBeInTheDocument();
// w trybie TV nie ma topbaru: brak Selectu zakresu i przełącznika zgody
expect(screen.queryByRole('combobox', { name: 'Zakres tablicy' })).not.toBeInTheDocument();
expect(screen.queryByRole('switch')).not.toBeInTheDocument();
});
});