Files
FitOS/app/test/trainee-plans.test.tsx

510 lines
19 KiB
TypeScript
Raw 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, waitFor, 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';
const TRAINEE_ID = 'trainee-1';
const USER = {
id: 'trainer-1',
email: 'trener@test.local',
firstName: 'Tomasz',
lastName: 'Trener',
age: 35,
heightCm: 185,
phone: null,
isAdmin: false,
availability: null,
priorities: 'chest',
exclusions: 'knee',
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-01T10:00:00.000Z',
};
const OTHER_TRAINER = { id: 'trainer-2', firstName: 'Jan', lastName: 'Kowalski' };
const EXERCISES = [
{ id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
{ id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
];
const TRAINEE_DETAIL = {
user: { id: TRAINEE_ID, firstName: 'Anna', lastName: 'Nowak' },
gyms: [{ id: 'gym-1', name: 'Siłownia Podopiecznej', equipment: [] }],
activePlan: null,
progress: null,
killstreak: 0,
nextTraining: null,
extra: null,
missing: null,
lastSessionAt: null,
flags: [],
};
const PLANS = [
{
id: 'plan-1',
title: 'Plan masowy',
status: 'DRAFT',
weeksCount: 1,
startDate: null,
creator: OTHER_TRAINER,
weeks: [],
},
{
id: 'plan-2',
title: 'Plan aktywny',
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-08-24',
creator: null,
weeks: [],
},
];
const DRAFT_DETAIL = {
id: 'plan-1',
title: 'Plan masowy',
status: 'DRAFT',
weeksCount: 1,
startDate: null,
creator: OTHER_TRAINER,
weeks: [
{
id: 'w1',
index: 0,
days: [
{
id: 'd1',
dayOfWeek: 1,
date: null,
status: 'PLANNED',
moveLog: [],
sessions: [],
exercises: [
{
id: 'pe1',
exerciseId: 'ex-1',
order: 0,
exercise: { id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
sets: [
{
id: 's1',
index: 0,
reps: 10,
loadKg: 60,
restSec: 90,
rir: 2,
cardioBpm: null,
timeSec: null,
speed: null,
},
],
},
],
},
],
},
],
};
const ACTIVE_DETAIL = {
id: 'plan-2',
title: 'Plan aktywny',
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-08-24',
creator: null,
weeks: [
{
id: 'w1',
index: 0,
days: [
{
id: 'd1',
dayOfWeek: 1,
date: '2026-08-24',
status: 'PLANNED',
moveLog: [],
sessions: [],
exercises: [
{
id: 'pe2',
exerciseId: 'ex-2',
order: 0,
exercise: { id: 'ex-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
sets: [
{
id: 's2',
index: 0,
reps: 8,
loadKg: 40,
restSec: 90,
rir: 2,
cardioBpm: null,
timeSec: null,
speed: null,
},
],
},
],
},
],
},
],
};
const LATEST_RESULTS = [
{
exerciseId: 'ex-1',
name: 'Przysiady',
muscle: 'legs',
date: '2026-08-20',
sets: [{ reps: 12, loadKg: 70 }],
oneRm: 80.6,
},
];
const PROGRESS = [
{
exerciseId: 'ex-1',
name: 'Przysiady',
muscle: 'legs',
points: [
{ date: '2026-08-13', oneRm: 75, volumeKg: 420, reps: 30, sets: 3 },
{ date: '2026-08-20', oneRm: 80.6, volumeKg: 480, reps: 36, sets: 3 },
],
},
];
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function mockApi(
opts: { plans?: unknown[]; capture?: { createBody?: Record<string, unknown> } } = {},
) {
const plans = opts.plans ?? PLANS;
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method || 'GET';
if (url.includes('/auth/refresh'))
return jsonResponse(200, { user: USER, accessToken: 'tok-1' });
if (url.includes('/me/active-session')) return jsonResponse(200, { session: null });
if (url.endsWith('/me'))
return jsonResponse(200, {
user: USER,
memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }],
});
if (url.includes('/dashboard'))
return jsonResponse(200, {
killstreak: 0,
activePlan: null,
nextTraining: null,
progress: null,
extra: null,
missing: null,
});
if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] });
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
if (url.includes('/exercises')) return jsonResponse(200, { exercises: EXERCISES });
// najpierw szczegóły planu (URL zawiera też /plans i /trainees/:id)
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/plans/plan-1`)) {
if (method === 'PATCH' || method === 'DELETE') return jsonResponse(200, { ok: true });
return jsonResponse(200, { plan: DRAFT_DETAIL });
}
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/plans/plan-2`))
return jsonResponse(200, { plan: ACTIVE_DETAIL });
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/plans`)) {
if (method === 'POST') {
if (opts.capture) opts.capture.createBody = JSON.parse(String(init?.body));
return jsonResponse(201, { plan: { id: 'plan-new' } });
}
return jsonResponse(200, { plans });
}
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/exercise-latest`))
return jsonResponse(200, { results: LATEST_RESULTS });
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/exercise-progress`))
return jsonResponse(200, { exercises: PROGRESS });
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/history`))
return jsonResponse(200, { sessions: [] });
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/report`))
return jsonResponse(200, { plan: null, muscles: [], days: [] });
if (url.includes(`/trainer/trainees/${TRAINEE_ID}/moves`))
return jsonResponse(200, { moves: [] });
if (url.includes(`/trainer/trainees/${TRAINEE_ID}`)) return jsonResponse(200, TRAINEE_DETAIL);
return jsonResponse(200, {});
}),
);
}
function renderAt(path: string) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={[path]}>
<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('Zakładka „Plany" w panelu podopiecznego', () => {
it('lista planów z badge statusu i etykietą twórcy; „Utwórz plan" w menu kontekstowym', async () => {
mockApi();
renderAt(`/trainees/${TRAINEE_ID}?tab=plans`);
expect(await screen.findByRole('heading', { name: 'Anna Nowak' })).toBeInTheDocument();
await screen.findByRole('heading', { name: 'Plany podopiecznego' });
// akcja tworzenia planu jest w menu kontekstowym strony (topbar), nie w zakładce
expect(screen.getByRole('button', { name: 'Utwórz plan' })).toBeInTheDocument();
expect(screen.getByText('Plan masowy')).toBeInTheDocument();
expect(screen.getByText('Plan aktywny')).toBeInTheDocument();
// badge statusu
expect(screen.getByText('Szkic')).toBeInTheDocument();
expect(screen.getByText('Aktywny')).toBeInTheDocument();
// etykieta twórcy (twórca ≠ zalogowany trener)
expect(screen.getByText('utworzył: Jan Kowalski')).toBeInTheDocument();
});
it('pusty stan, gdy podopieczny nie ma planów', async () => {
mockApi({ plans: [] });
renderAt(`/trainees/${TRAINEE_ID}?tab=plans`);
expect(await screen.findByRole('heading', { name: 'Plany podopiecznego' })).toBeInTheDocument();
expect(screen.getByText('Podopieczny nie ma żadnych planów.')).toBeInTheDocument();
});
it('szkic: akcje Edytuj/Aktywuj/Usuń i struktura inline', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}?tab=plans`);
await screen.findByRole('heading', { name: 'Plany podopiecznego' });
await user.click(screen.getByRole('button', { name: 'Plan masowy' }));
expect(await screen.findByRole('button', { name: 'Edytuj' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Aktywuj' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Usuń' })).toBeInTheDocument();
// struktura inline (nagłówek akordeonu — pasek tygodni ma też chip „Tydzień 1”)
expect(screen.getByRole('heading', { name: 'Tydzień 1' })).toBeInTheDocument();
expect(screen.getByText('Poniedziałek')).toBeInTheDocument();
expect(screen.getByText(/Przysiady/)).toBeInTheDocument();
});
it('aktywny: akcje „Oznacz jako ukończony" i „Porzuć"', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}?tab=plans`);
await screen.findByRole('heading', { name: 'Plany podopiecznego' });
await user.click(screen.getByRole('button', { name: 'Plan aktywny' }));
expect(await screen.findByRole('button', { name: 'Porzuć' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Oznacz jako ukończony' })).toBeInTheDocument();
});
});
describe('PlanEditor — tryb podopiecznego', () => {
it('edycja: formularz inicjalizuje się z danych planu po załadowaniu', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/plan-1/edit`);
expect(
await screen.findByRole('heading', { name: 'Edycja planu podopiecznego' }),
).toBeInTheDocument();
// tytuł wczytany z API (krok 1); serie (krok 2) po przejściu „Dalej”
expect(await screen.findByDisplayValue('Plan masowy')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Dalej' }));
expect(await screen.findByDisplayValue('60')).toBeInTheDocument();
});
it('„Wstecz" przy niezapisanych zmianach pyta o potwierdzenie', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
// zmiana tytułu → stan dirty
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'X');
// „Wstecz” w treści (w jsdom jest też „<” topbara mobile — oba prowadzą do guardu)
await user.click(screen.getAllByRole('button', { name: 'Wstecz' }).at(-1)!);
expect(await screen.findByRole('heading', { name: 'Niezapisane zmiany' })).toBeInTheDocument();
// potwierdzenie → powrót do zakładki planów podopiecznego
await user.click(screen.getByRole('button', { name: 'Opuść' }));
expect(await screen.findByRole('heading', { name: 'Plany podopiecznego' })).toBeInTheDocument();
});
it('karta ćwiczenia: badge grupy mięśniowej i podsumowanie serii', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
// krok 2 (ćwiczenia) — po tytule i przejściu „Dalej”
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
await user.click(await screen.findByRole('option', { name: /Przysiady/ }));
// legs → badge „Nogi”; seria domyślna → „1×10 @ 20 kg · RIR 2”
expect(screen.getByText('Nogi')).toBeInTheDocument();
expect(screen.getByText(/1×10 @ 20 kg/)).toBeInTheDocument();
});
it('„Wstecz” na kroku 2 cofa do kroku 1 (nie wychodzi z edytora)', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
// pole siłowni = krok 1
expect(screen.getByText('Siłownia')).toBeInTheDocument();
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// krok 2: tytuł schowany — jesteśmy na etapie ćwiczeń
expect(screen.queryByPlaceholderText('np. Plan masowy 8-tygodniowy')).not.toBeInTheDocument();
// „Wstecz” w treści (ostatni w DOM) cofa do kroku 1
await user.click(screen.getAllByRole('button', { name: 'Wstecz' }).at(-1)!);
expect(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy')).toBeVisible();
expect(screen.getByText('Siłownia')).toBeInTheDocument();
});
it('walidacja: pusty tytuł blokuje „Dalej” i „Zapisz”', async () => {
mockApi();
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
expect(screen.getByRole('button', { name: 'Dalej' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Zapisz' })).toBeDisabled();
});
it('„Wstaw wyniki" prefylluje serie z ostatniej sesji', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
expect(
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' }),
).toBeInTheDocument();
// krok 2 (ćwiczenia) — po tytule i przejściu „Dalej”
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// dodaj dzień (Poniedziałek — aria-label z pełną nazwą)
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
// dodaj ćwiczenie Przysiady (wyszukiwarka ćwiczeń)
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
await user.click(await screen.findByRole('option', { name: /Przysiady/ }));
// otwórz panel wyników i wstaw
await user.click(screen.getByRole('button', { name: 'Wyniki' }));
expect(await screen.findByText('Wstaw wyniki')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Wstaw wyniki' }));
// serie z ostatniej sesji: 12 powt. @ 70 kg
expect(screen.getByDisplayValue('12')).toBeInTheDocument();
expect(screen.getByDisplayValue('70')).toBeInTheDocument();
});
});
describe('PlanEditor — wizard 3-etapowy (tryb podopiecznego)', () => {
it('krok 1 blokuje „Dalej” przy pustym tytule', async () => {
mockApi();
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
expect(screen.getByRole('button', { name: 'Dalej' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'Zapisz' })).toBeDisabled();
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
expect(screen.getByRole('button', { name: 'Dalej' })).toBeEnabled();
expect(screen.getByRole('button', { name: 'Zapisz' })).toBeEnabled();
});
it('krok 2: select siłowni z członkostw podopiecznego + alias tygodnia; krok 3: podsumowanie i zapis', async () => {
const capture: { createBody?: Record<string, unknown> } = {};
mockApi({ capture });
const user = userEvent.setup();
renderAt(`/trainees/${TRAINEE_ID}/plans/new`);
await screen.findByRole('heading', { name: 'Plan dla podopiecznego' });
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan wizard');
// 1 tydzień — podsumowanie bez lustrzanych tygodni
const weeksField = screen
.getByText('Długość (tygodnie)')
.closest('[data-slot="field"]') as HTMLElement;
await user.selectOptions(within(weeksField).getByRole('combobox'), '1');
// select siłowni (krok 1): opcja „Bez siłowni” + siłownia podopiecznego
// (Field bez <label for> — selekcja przez kontener pola)
const gymField = screen.getByText('Siłownia').closest('[data-slot="field"]') as HTMLElement;
const gymSelect = within(gymField).getByRole('combobox');
expect(within(gymSelect).getByRole('option', { name: 'Bez siłowni' })).toBeInTheDocument();
expect(
within(gymSelect).getByRole('option', { name: 'Siłownia Podopiecznej' }),
).toBeInTheDocument();
await user.selectOptions(gymSelect, 'gym-1');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// krok 2: dzień + ćwiczenie + alias tygodnia
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
await user.click(await screen.findByRole('option', { name: /Przysiady/ }));
const aliasField = screen
.getByText('Nazwa tygodnia 1 (opcjonalnie)')
.closest('[data-slot="field"]') as HTMLElement;
await user.type(within(aliasField).getByRole('textbox'), 'Deload');
// krok 3: podsumowanie — alias, siłownia, dni i ćwiczenia
await user.click(screen.getByRole('button', { name: 'Dalej' }));
expect(await screen.findByText('Deload')).toBeInTheDocument();
expect(screen.getByText('Siłownia Podopiecznej')).toBeInTheDocument();
// liczniki w karcie podsumowania („Łącznie:” = unikalne; stopka na kroku 3 ukryta)
const summaryCard = screen
.getByText('Łącznie: 1 dzień · 1 ćwiczenie · 1 seria')
.closest('[data-slot="card"]') as HTMLElement;
expect(
within(summaryCard).getByText('Pon · 1 dzień · 1 ćwiczenie · 1 seria'),
).toBeInTheDocument();
// zapis (krok 3) — body z gymId i customName
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
await waitFor(() => expect(capture.createBody).toBeDefined());
expect(capture.createBody).toMatchObject({
title: 'Plan wizard',
gymId: 'gym-1',
weeks: [expect.objectContaining({ index: 0, customName: 'Deload' })],
});
});
});