Files
FitOS/app/test/PlanEditor.test.tsx

872 lines
40 KiB
TypeScript

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';
import type { Equipment, GymEquipment, 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: null,
isAdmin: false,
availability: null,
priorities: 'chest',
exclusions: 'knee',
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-22T10:00:00.000Z',
};
const EQ_BARBELL: Equipment = {
id: 'eq-1',
name: 'Sztanga',
kind: 'BARBELL',
spec: null,
description: null,
};
const EQ_BODYWEIGHT: Equipment = {
id: 'eq-bw',
name: 'Masa ciała',
kind: 'BODYWEIGHT',
spec: null,
description: null,
};
const EQ_CABLE: Equipment = {
id: 'eq-4',
name: 'Wyciąg',
kind: 'CABLE',
spec: null,
description: null,
};
const EXERCISES = [
{ id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs', equipment: [EQ_BARBELL] },
{ id: 'ex-2', name: 'Pompki', primaryMuscle: 'chest', equipment: [EQ_BODYWEIGHT] },
{ id: 'ex-3', name: 'Wyciskanie na wyciągu', primaryMuscle: 'chest', equipment: [EQ_CABLE] },
];
/** Wyposażenie gym-1: tylko sztanga (wyciągu brak). */
const GYM_EQ: GymEquipment[] = [
{ id: 'ge-1', gymId: 'gym-1', equipmentId: 'eq-1', quantity: 1, equipment: EQ_BARBELL },
];
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
interface Capture {
createPlanBody?: Record<string, unknown>;
patchPlanBody?: Record<string, unknown>;
}
function mockApi(
capture: Capture,
gyms: { id: string; name: string; equipment?: GymEquipment[] }[] = [],
) {
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/active-session')) return jsonResponse(200, { session: null });
if (url.endsWith('/me')) return jsonResponse(200, { user: USER, memberships: [] });
if (url.includes('/exercises')) return jsonResponse(200, { exercises: EXERCISES });
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('/plans/plan-new'))
return jsonResponse(200, {
plan: {
id: 'plan-new',
title: 'Plan testowy',
status: 'ACTIVE',
weeksCount: 4,
startDate: '2026-08-24',
weeks: [],
},
});
if (url.endsWith('/plans')) {
if (method === 'POST') {
capture.createPlanBody = JSON.parse(String(init?.body));
return jsonResponse(201, { plan: { id: 'plan-new' } });
}
return jsonResponse(200, { plans: [] });
}
return jsonResponse(200, {});
}),
);
}
function renderApp() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
}
async function loginAndOpenNewPlan(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: 'Plany treningowe' }));
expect(await screen.findByRole('heading', { name: 'Plany treningowe' })).toBeInTheDocument();
// „Nowy plan” pojawia się w menu kontekstowym i w pustym stanie listy — klikamy pierwsze (menu)
await user.click(screen.getAllByRole('button', { name: 'Nowy plan' })[0]);
expect(await screen.findByRole('heading', { name: 'Nowy plan' })).toBeInTheDocument();
}
/* Komórka serii to picker kółkowy — testy wpisują wartość deterministycznie
przez tryb ręczny „Wpisz” w bottom sheecie. */
async function setSetField(user: userEvent.User, fieldAria: string, value: string) {
await user.click(screen.getByRole('button', { name: fieldAria }));
const dialog = await screen.findByRole('dialog');
await user.click(within(dialog).getByRole('button', { name: 'Wpisz' }));
const input = within(dialog).getByRole('textbox', { name: fieldAria });
await user.clear(input);
await user.type(input, value);
await user.click(within(dialog).getByRole('button', { name: 'Zapisz' }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('PlanEditor — data startu i menu kontekstowe', () => {
it('ma wybór tygodnia startu i przekazuje jego poniedziałek do createPlan', async () => {
const capture: Capture = {};
mockApi(capture);
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
// wybór tygodnia startu jest widoczny w trybie tworzenia
expect(screen.getByRole('group', { name: 'Wybór tygodnia startu' })).toBeInTheDocument();
// 20. dzień bieżącego miesiąca może być w minionym tygodniu (zablokowany) —
// wybieramy 20. dzień następnego miesiąca (unikalny w siatce, zawsze przyszły tydzień)
await user.click(screen.getByRole('button', { name: 'Następny miesiąc' }));
await user.click(screen.getByRole('button', { name: '20' }));
// oczekiwany poniedziałek tygodnia zawierającego 20. dzień następnego miesiąca
const now = new Date();
const target = new Date(now.getFullYear(), now.getMonth() + 1, 20);
const monday = new Date(target);
monday.setDate(target.getDate() - ((target.getDay() + 6) % 7));
const expected = `${monday.getFullYear()}-${String(monday.getMonth() + 1).padStart(2, '0')}-${String(
monday.getDate(),
).padStart(2, '0')}`;
const title = screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy');
await user.type(title, 'Plan testowy');
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
await waitFor(() =>
expect(capture.createPlanBody).toMatchObject({
title: 'Plan testowy',
startDate: expected,
}),
);
});
it('blokuje minione tygodnie startu', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
// siatka = 42 komórki (6 tygodni) z dniami sąsiednich miesięcy — dla KAŻDEJ komórki
// oczekiwany stan bierze się z poniedziałka jej tygodnia (ten sam numer dnia może
// występować w minionym i przyszłym tygodniu, więc sprawdzamy komórkę po komórce)
const now = new Date();
const y = now.getFullYear();
const m = now.getMonth() + 1;
const firstDay = new Date(y, m - 1, 1);
const startOffset = (firstDay.getDay() + 6) % 7;
const gridStart = new Date(y, m - 1, 1 - startOffset);
const cells = Array.from({ length: 42 }, (_, i) => {
const d = new Date(gridStart);
d.setDate(gridStart.getDate() + i);
return d;
});
const mondayOf = (d: Date) => {
const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
return x;
};
const curMonday = mondayOf(now);
const group = screen.getByRole('group', { name: 'Wybór tygodnia startu' });
const buttons = within(group).getAllByRole('button');
expect(buttons).toHaveLength(42);
for (let i = 0; i < 42; i++) {
expect((buttons[i] as HTMLButtonElement).disabled).toBe(mondayOf(cells[i]) < curMonday);
}
});
it('nie wysyła startDate, gdy nie zaznaczono tygodnia startu', async () => {
const capture: Capture = {};
mockApi(capture);
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
const title = screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy');
await user.type(title, 'Plan szkic');
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
await waitFor(() => expect(capture.createPlanBody).toBeDefined());
expect(capture.createPlanBody).not.toHaveProperty('startDate');
});
it('wizard: krok 1 blokuje „Dalej” bez tytułu; select siłowni z /gyms w kroku 1; zapis z gymId i aliasem', async () => {
const capture: Capture = {};
mockApi(capture, [{ id: 'gym-1', name: 'Siłownia Testowa', equipment: GYM_EQ }]);
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
// krok 1: „Dalej” zablokowany przy pustym tytule
expect(screen.getByRole('button', { name: 'Dalej' })).toBeDisabled();
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan wizard');
expect(screen.getByRole('button', { name: 'Dalej' })).toBeEnabled();
// 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');
// krok 1: select siłowni (członkostwa zalogowanego) — decyzja przed układaniem treningów
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 Testowa' })).toBeInTheDocument();
await user.selectOptions(gymSelect, 'gym-1');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// krok 2: dzień + ćwiczenie + alias tygodnia (w panelu 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/ }));
await user.click(screen.getByRole('button', { name: 'Tydzień 1 (zmień nazwę)' }));
await user.type(screen.getByRole('textbox', { name: 'Nazwa tygodnia 1' }), 'Deload');
await user.keyboard('{Enter}');
// krok 3: podsumowanie — siłownia, alias, „szkic — bez startu”, liczniki
await user.click(screen.getByRole('button', { name: 'Dalej' }));
expect(await screen.findByText('Deload')).toBeInTheDocument();
expect(screen.getByText('Siłownia Testowa')).toBeInTheDocument();
expect(screen.getByText('szkic — bez startu')).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 — body z gymId i customName
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
await waitFor(() => expect(capture.createPlanBody).toBeDefined());
expect(capture.createPlanBody).toMatchObject({
title: 'Plan wizard',
gymId: 'gym-1',
weeks: [expect.objectContaining({ index: 0, customName: 'Deload' })],
});
});
it('siłownia z kroku 1 limituje ćwiczenia do jej sprzętu (masa ciała zawsze dostępna)', async () => {
const capture: Capture = {};
mockApi(capture, [{ id: 'gym-1', name: 'Siłownia Testowa', equipment: GYM_EQ }]);
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan sprzęt');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// bez siłowni: pełny katalog, bez podpowiedzi o sprzęcie
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
expect(await screen.findByRole('option', { name: /Przysiady/ })).toBeInTheDocument();
expect(screen.getByRole('option', { name: /Pompki/ })).toBeInTheDocument();
expect(screen.getByRole('option', { name: /Wyciskanie na wyciągu/ })).toBeInTheDocument();
expect(screen.queryByText(/Tylko sprzęt siłowni/)).not.toBeInTheDocument();
await user.keyboard('{Escape}');
// powrót do kroku 1 (stepper): po wybraniu siłowni (ma tylko sztangę) wyciąg znika, masa ciała zostaje
await user.click(screen.getByRole('button', { name: 'Szczegóły' }));
const gymField = screen.getByText('Siłownia').closest('[data-slot="field"]') as HTMLElement;
await user.selectOptions(within(gymField).getByRole('combobox'), 'gym-1');
await user.click(screen.getByRole('button', { name: 'Ćwiczenia' }));
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
expect(await screen.findByRole('option', { name: /Przysiady/ })).toBeInTheDocument();
expect(screen.getByRole('option', { name: /Pompki/ })).toBeInTheDocument();
expect(screen.queryByRole('option', { name: /Wyciskanie na wyciągu/ })).not.toBeInTheDocument();
expect(screen.getByText(/Tylko sprzęt siłowni/)).toBeInTheDocument();
});
it('krok 2: tabela serii ma podstawowe kolumny, Przerwa/RIR pod „Więcej opcji”, nigdy „Trudność”', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
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/ }));
// domyślnie tylko Powt. / Obciążenie — bez Przerwy, RIR i „Trudności”
expect(screen.getByRole('columnheader', { name: 'Powt.' })).toBeInTheDocument();
expect(screen.getByRole('columnheader', { name: 'Obciążenie' })).toBeInTheDocument();
expect(screen.queryByRole('columnheader', { name: 'Przerwa' })).not.toBeInTheDocument();
expect(screen.queryByRole('columnheader', { name: 'RIR' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Seria 1: Trudność' })).not.toBeInTheDocument();
// „Więcej opcji” = pełna tabela (4 kolumny), wciąż bez „Trudności”
await user.click(screen.getByRole('button', { name: 'Więcej opcji' }));
expect(screen.getByRole('columnheader', { name: 'Przerwa' })).toBeInTheDocument();
expect(screen.getByRole('columnheader', { name: 'RIR' })).toBeInTheDocument();
expect(screen.queryByRole('columnheader', { name: 'Trudność' })).not.toBeInTheDocument();
});
it('krok 2: stepper „Serie” kopiuje ostatnią serię („+”) i usuwa ostatnią („−”)', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
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/ }));
// „−” zablokowany przy jednej serii
expect(screen.getByRole('button', { name: 'Usuń ostatnią serię' })).toBeDisabled();
// zmień pierwszą serię → „+” dodaje jej kopię (nie pustą domyślną)
await setSetField(user, 'Seria 1: Powt.', '8');
await user.click(screen.getByRole('button', { name: 'Dodaj serię' }));
expect(screen.getByRole('button', { name: 'Seria 2: Powt.' })).toHaveTextContent('8');
await user.click(screen.getByRole('button', { name: 'Dodaj serię' }));
expect(screen.getByRole('button', { name: 'Seria 3: Powt.' })).toHaveTextContent('8');
await user.click(screen.getByRole('button', { name: 'Usuń ostatnią serię' }));
expect(screen.queryByRole('button', { name: 'Seria 3: Powt.' })).not.toBeInTheDocument();
});
it('wizard: pusta lista siłowni — informacja z linkiem do /gyms (krok 1)', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
expect(screen.getByText('Nie należysz do żadnej siłowni.')).toBeInTheDocument();
expect(screen.getByRole('link', { name: 'Zarządzaj siłowniami' })).toBeInTheDocument();
});
it('krok 2: lustrzany tydzień pokazuje podgląd tygodnia 1; „Edytuj samodzielnie” odłącza', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
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/ }));
// zakładka tygodnia 3 (domyślnie 4 tygodnie) — lustrzany: podgląd zamiast edytora dni
// (nazwa taba = „T.3” + „Tydzień 3” — w jsdom obie etykiety viewportowe wliczają się do accessible name)
await user.click(screen.getByRole('button', { name: /Tydzień 3/ }));
expect(screen.getByText('Ten tydzień powtarza tydzień 1.')).toBeInTheDocument();
expect(screen.getByText('Poniedziałek')).toBeInTheDocument();
expect(screen.queryByRole('group', { name: 'Dni treningowe' })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Edytuj samodzielnie' })).toBeInTheDocument();
// jawne odłączenie → edytor dni z niezależną kopią dnia z tygodnia 1
await user.click(screen.getByRole('button', { name: 'Edytuj samodzielnie' }));
const dayGroup = screen.getByRole('group', { name: 'Dni treningowe' });
expect(
within(dayGroup).getByRole('button', { name: 'Poniedziałek', pressed: true }),
).toBeInTheDocument();
expect(screen.getByText('Przysiady')).toBeInTheDocument();
});
it('krok 2: klik w siatce dni przełącza edytowany dzień (nigdy nie usuwa; brak strzałek)', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan dni');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// Pon + ćwiczenie; strzałki steppera zniknęły na dobre — siatka to jedyna nawigacja
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/ }));
expect(
screen.getByRole('heading', { name: 'Planujesz teraz Poniedziałek' }),
).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Następny dzień' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Poprzedni dzień' })).not.toBeInTheDocument();
// dodanie Środy (szara komórka) przenosi edycję na nią; nazwa dnia = siatka + nagłówek
const dayGroup = screen.getByRole('group', { name: 'Dni treningowe' });
await user.click(within(dayGroup).getByRole('button', { name: 'Środa' }));
expect(screen.getByRole('heading', { name: 'Planujesz teraz Środa' })).toBeInTheDocument();
expect(screen.queryByText('Przysiady')).not.toBeInTheDocument();
expect(screen.getAllByRole('button', { name: 'Środa' })).toHaveLength(1);
// klik w pomarańczowy, nieedytowany dzień = przełączenie edytora — NIE usuwanie
await user.click(within(dayGroup).getByRole('button', { name: 'Poniedziałek' }));
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(
screen.getByRole('heading', { name: 'Planujesz teraz Poniedziałek' }),
).toBeInTheDocument();
expect(screen.getByText('Przysiady')).toBeInTheDocument();
expect(screen.getByText('1 ćwiczenie')).toBeInTheDocument();
// edytowany dzień wyróżniony (aria-current); klik w niego ponownie = no-op bez dialogu
expect(within(dayGroup).getByRole('button', { name: 'Poniedziałek' })).toHaveAttribute(
'aria-current',
'true',
);
expect(within(dayGroup).getByRole('button', { name: 'Środa' })).not.toHaveAttribute(
'aria-current',
);
await user.click(within(dayGroup).getByRole('button', { name: 'Poniedziałek' }));
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
expect(
screen.getByRole('heading', { name: 'Planujesz teraz Poniedziałek' }),
).toBeInTheDocument();
});
it('krok 2: kosze w nagłówku dnia usuwają dzień z ćwiczeniami po potwierdzeniu', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
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/ }));
await user.click(screen.getByRole('button', { name: 'Usuń dzień' }));
expect(await screen.findByRole('heading', { name: 'Usunąć dzień?' })).toBeInTheDocument();
const dialog = screen.getByRole('dialog');
// sam kosze nie kasuje — dopiero potwierdzenie w dialogu
expect(within(dialog).getByText(/Usunąć poniedziałek i jego 1 ćwiczenie/)).toBeInTheDocument();
await user.click(within(dialog).getByRole('button', { name: 'Usuń dzień' }));
expect(await screen.findByText('Brak dni treningowych')).toBeInTheDocument();
expect(
within(screen.getByRole('group', { name: 'Dni treningowe' })).getByRole('button', {
name: 'Poniedziałek',
pressed: false,
}),
).toBeInTheDocument();
});
it('krok 2: „Kopiuj z…” pozwala skopiować dni z dowolnego tygodnia (nie tylko poprzedniego)', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// tydzień 1: Poniedziałek + ćwiczenie
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/ }));
// tydzień 2: odłącz i dodaj Środę → źródło różne od tygodnia 1
await user.click(screen.getByRole('button', { name: /Tydzień 2/ }));
await user.click(screen.getByRole('button', { name: 'Edytuj samodzielnie' }));
await user.click(
within(screen.getByRole('group', { name: 'Dni treningowe' })).getByRole('button', {
name: 'Środa',
}),
);
// tydzień 4: kopiuj z tygodnia 2 (źródło nie jest poprzednie względem celu)
await user.click(screen.getByRole('button', { name: /Tydzień 4/ }));
await user.click(screen.getByRole('button', { name: 'Akcje tygodnia' }));
await user.click(screen.getByRole('button', { name: 'Kopiuj z…' }));
expect(screen.getByText('2 dni · 1 ćwiczenie')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Kopiuj: Tydzień 4' })).not.toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Kopiuj: Tydzień 2' }));
// cel przejął dni źródła i stał się samodzielny (banner lustrzany zniknął)
expect(screen.queryByText('Ten tydzień powtarza tydzień 1.')).not.toBeInTheDocument();
const dayGroup = screen.getByRole('group', { name: 'Dni treningowe' });
expect(
within(dayGroup).getByRole('button', { name: 'Poniedziałek', pressed: true }),
).toBeInTheDocument();
expect(
within(dayGroup).getByRole('button', { name: 'Środa', pressed: true }),
).toBeInTheDocument();
expect(screen.getByText('Przysiady')).toBeInTheDocument();
});
it('krok 2: „Kopiuj dzień z…” na niepusty dzień pyta „Nadpisz”; anuluj zostawia treść, potwierdzenie podmienia', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
await user.type(screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'), 'Plan');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// tydzień 1: Poniedziałek + Przysiady, Środa + Wyciskanie
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/ }));
await user.click(screen.getByRole('button', { name: 'Środa' }));
await user.click(screen.getByRole('button', { name: 'dodaj ćwiczenie…' }));
await user.click(await screen.findByRole('option', { name: /Wyciskanie/ }));
// modal źródeł: grupy po tygodniach — „Ten tydzień” + lustrzane tygodnie z dniami 1
await user.click(screen.getByRole('button', { name: 'Kopiuj dzień z…' }));
const modal = await screen.findByRole('dialog');
expect(within(modal).getByText('Ten tydzień')).toBeInTheDocument();
expect(within(modal).getByText('Tydzień 2', { exact: true })).toBeInTheDocument();
expect(within(modal).getByRole('button', { name: 'Kopiuj: Poniedziałek' })).toBeInTheDocument();
expect(
within(modal).getByRole('button', { name: 'Kopiuj: Tydzień 2 — Poniedziałek' }),
).toBeInTheDocument();
await user.click(within(modal).getByRole('button', { name: 'Kopiuj: Poniedziałek' }));
// Środa ma ćwiczenia (bez historii) — wymagane potwierdzenie nadpisania
expect(await screen.findByRole('heading', { name: 'Nadpisać środę?' })).toBeInTheDocument();
const overwrite = screen.getByRole('dialog');
expect(
within(overwrite).getByText(
/środa ma 1 ćwiczenie\. Kopiowanie zastąpi je treścią dnia Poniedziałek/,
),
).toBeInTheDocument();
await user.click(within(overwrite).getByRole('button', { name: 'Anuluj' }));
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
expect(screen.queryByText('Przysiady')).not.toBeInTheDocument();
expect(screen.getByText('Wyciskanie na wyciągu')).toBeInTheDocument();
// potwierdzenie: treść podmieniona (bez forceRemoveDays — brak historii)
await user.click(screen.getByRole('button', { name: 'Kopiuj dzień z…' }));
const modal2 = await screen.findByRole('dialog');
await user.click(within(modal2).getByRole('button', { name: 'Kopiuj: Poniedziałek' }));
await user.click(
await screen.findByRole('button', {
name: 'Nadpisz',
}),
);
expect(screen.getByText('Przysiady')).toBeInTheDocument();
expect(screen.queryByText('Wyciskanie na wyciągu')).not.toBeInTheDocument();
expect(screen.getByText('1 ćwiczenie')).toBeInTheDocument();
});
it('pokazuje „Wstecz” w treści formularza na /plans/new', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
// „Wstecz” w treści strony (BackButton, md+); topbar ma osobną ikonę „<” (mobile)
const content = document.querySelector('main .max-w-5xl');
expect(content).not.toBeNull();
expect(within(content!).getByRole('button', { name: 'Wstecz' })).toBeInTheDocument();
});
it('topmenu edytora: akcje inline od md+ (bez akordeonu „⋯”), pojedyncze „Wstecz”', async () => {
mockApi({});
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
const header = document.querySelector('header')!;
// ikona grupy ⋯ zawsze ukryta: telefon = płaski rząd w pasku, md+ = inline w nagłówku
const actionsIcon = header.querySelector('button[aria-label="Akcje"]') as HTMLElement;
expect(actionsIcon.className).toContain('hidden');
// panel akcji inline od md+
const panel = actionsIcon.previousElementSibling as HTMLElement;
expect(panel.className).toContain('md:flex');
// akcje widoczne w nagłówku bez otwierania menu
expect(within(header).getByRole('button', { name: 'Dalej' })).toBeInTheDocument();
expect(within(header).getByRole('button', { name: 'Zapisz' })).toBeInTheDocument();
// „Wstecz” w topbarze = ikona „<” (mobile); na md+ BackButton w treści
const backIcon = header.querySelector('button[aria-label="Wstecz"]') as HTMLElement;
expect(backIcon.className).toContain('md:hidden');
});
});
/** Aktywny plan z jednym dniem/ćwiczeniem/serią — wiersze z id do edycji różnicowej. */
function activePlan() {
return {
id: 'plan-1',
userId: 'u1',
title: 'Plan w trakcie',
status: 'ACTIVE',
weeksCount: 1,
startDate: '2026-08-24',
gym: null,
creator: null,
canManage: true,
weeks: [
{
id: 'tw-1',
index: 0,
customName: null,
days: [
{
id: 'td-1',
dayOfWeek: 1,
date: '2026-08-24T00:00:00.000Z',
status: 'PLANNED',
moveLog: [],
sessions: [],
exercises: [
{
id: 'tpe-1',
exerciseId: 'ex-1',
order: 0,
exercise: { id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
sets: [
{
id: 'tps-1',
index: 0,
reps: 10,
loadKg: 60,
restSec: 90,
rir: 2,
cardioBpm: null,
timeSec: null,
speed: null,
},
],
},
],
},
],
},
],
};
}
function mockEditApi(capture: Capture, plan: Record<string, unknown>) {
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/active-session')) return jsonResponse(200, { session: null });
if (url.endsWith('/me')) return jsonResponse(200, { user: USER, memberships: [] });
if (url.includes('/exercises')) return jsonResponse(200, { exercises: EXERCISES });
if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] });
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
if (url.endsWith('/plans')) return jsonResponse(200, { plans: [plan] });
if (url.endsWith('/plans/plan-1') && method === 'PATCH') {
capture.patchPlanBody = JSON.parse(String(init?.body));
return jsonResponse(200, { ok: true });
}
if (url.includes('/plans/plan-1')) return jsonResponse(200, { plan });
return jsonResponse(200, {});
}),
);
}
async function loginAndOpenEditor(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: 'Plany treningowe' }));
expect(await screen.findByRole('heading', { name: 'Plany treningowe' })).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan w trakcie' })).toBeInTheDocument();
// akcja „Edytuj” w topmenu (PlanDetail) prowadzi do edytora
await user.click(
within(document.querySelector('header')!).getByRole('button', { name: 'Edytuj' }),
);
}
describe('PlanEditor — edycja aktywnego planu (opcjonalna notatka + id wierszy)', () => {
it('start planu zablokowany, notatka opcjonalna; zapis bez notatki = PATCH bez changeNote z id dni/ćwiczeń/serii', async () => {
const capture: Capture = {};
const plan = activePlan();
mockEditApi(capture, plan);
const user = userEvent.setup();
renderApp();
await loginAndOpenEditor(user);
expect(await screen.findByRole('heading', { name: 'Edycja planu' })).toBeInTheDocument();
// krok 1 aktywnego planu: brak wyboru tygodnia startu, jest opcjonalna notatka o zmianach
expect(screen.queryByRole('group', { name: 'Wybór tygodnia startu' })).not.toBeInTheDocument();
expect(
screen.getByText('Plan jest realizowany — data startu jest niezmienna.'),
).toBeInTheDocument();
const noteField = screen
.getByText('Notatka o zmianach')
.closest('[data-slot="field"]') as HTMLElement;
expect(within(noteField).getByRole('textbox')).toBeInTheDocument();
// zmiana w kroku 2 (brudny edytor)
await user.click(screen.getByRole('button', { name: 'Dalej' }));
await setSetField(user, 'Seria 1: Powt.', '12');
// zapis bez notatki = PATCH bez changeNote (notatka opcjonalna, brak blokady)
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
await waitFor(() => expect(capture.patchPlanBody).toBeDefined());
expect(capture.patchPlanBody).not.toHaveProperty('changeNote');
expect(capture.patchPlanBody).toMatchObject({ title: 'Plan w trakcie' });
expect(capture.patchPlanBody).not.toHaveProperty('startDate');
const weeks = capture.patchPlanBody!.weeks as Record<string, unknown>[];
const day = (weeks[0].days as Record<string, unknown>[])[0];
expect(day.id).toBe('td-1');
const exercise = (day.exercises as Record<string, unknown>[])[0];
expect(exercise.id).toBe('tpe-1');
expect((exercise.sets as Record<string, unknown>[])[0]).toMatchObject({
id: 'tps-1',
reps: 12,
});
});
it('uzupełniona notatka trafia do PATCH jako changeNote', async () => {
const capture: Capture = {};
const plan = activePlan();
mockEditApi(capture, plan);
const user = userEvent.setup();
renderApp();
await loginAndOpenEditor(user);
await screen.findByRole('heading', { name: 'Edycja planu' });
const noteField = screen
.getByText('Notatka o zmianach')
.closest('[data-slot="field"]') as HTMLElement;
await user.type(within(noteField).getByRole('textbox'), 'Korekta po kontuzji');
await user.click(screen.getByRole('button', { name: 'Dalej' }));
await setSetField(user, 'Seria 1: Powt.', '12');
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
await waitFor(() => expect(capture.patchPlanBody).toBeDefined());
expect(capture.patchPlanBody).toMatchObject({
title: 'Plan w trakcie',
changeNote: 'Korekta po kontuzji',
});
});
});
describe('PlanEditor — dzień z historią w aktywnym planie', () => {
it('usunięcie dnia z historią: potwierdzenie „Usuń mimo historii”, zapis = PATCH z forceRemoveDays', async () => {
const capture: Capture = {};
const plan = activePlan();
const day = (plan.weeks as Record<string, unknown>[])[0].days as Record<string, unknown>[];
day[0].status = 'COMPLETED';
day[0].sessions = [{ id: 'ts-1', status: 'COMPLETED', startedAt: '2026-08-24T10:00:00.000Z' }];
mockEditApi(capture, plan);
const user = userEvent.setup();
renderApp();
await loginAndOpenEditor(user);
expect(await screen.findByRole('heading', { name: 'Edycja planu' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// dzień z historią: kłódka w a11y + badge „Historia” w nagłówku dnia
const lockedDay = await screen.findByRole('button', {
name: 'Poniedziałek — dzień z historią treningów',
});
expect(screen.getByText('Historia')).toBeInTheDocument();
// klik w siatce tylko nawiguje — usuwanie wyłącznie przez kosze w nagłówku dnia
await user.click(lockedDay);
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Usuń dzień' }));
expect(
await screen.findByRole('heading', { name: 'Usunąć dzień z historią?' }),
).toBeInTheDocument();
expect(screen.getByText(/historia treningowa zostanie zachowana/)).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Usuń mimo historii' }));
// zapis bez notatki = PATCH od razu (notatka opcjonalna)
await user.click(screen.getByRole('button', { name: 'Zapisz zmiany' }));
await waitFor(() => expect(capture.patchPlanBody).toBeDefined());
expect(capture.patchPlanBody).toMatchObject({ forceRemoveDays: true });
expect(capture.patchPlanBody).not.toHaveProperty('changeNote');
const weeks = capture.patchPlanBody!.weeks as Record<string, unknown>[];
expect((weeks[0].days as unknown[]).length).toBe(0);
});
});
describe('PlanEditor — dzień bez ćwiczeń blokuje zapis', () => {
it('dodanie dnia bez ćwiczeń: komunikat i skok do kroku 2 na pusty dzień', async () => {
const capture: Capture = {};
mockApi(capture);
const user = userEvent.setup();
renderApp();
await loginAndOpenNewPlan(user);
await user.type(
screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy'),
'Plan pusty dzień',
);
await user.click(screen.getByRole('button', { name: 'Dalej' }));
// dzień treningowy bez ćwiczeń (klik w siatce dni = dzień z 0 ćwiczeń)
await user.click(screen.getByRole('button', { name: 'Poniedziałek' }));
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByText(/dzień Poniedziałek nie ma ćwiczeń/)).toBeInTheDocument();
expect(capture.createPlanBody).toBeUndefined();
// edytor przenosi na krok 2 — siatka dni jest widoczna
expect(screen.getByRole('group', { name: 'Dni treningowe' })).toBeInTheDocument();
});
});