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

501 lines
22 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',
age: 30,
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>;
}
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' }));
expect(await screen.findByRole('heading', { name: 'Plany' })).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();
}
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/ }));
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 — 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('textbox', { 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ą)
const reps1 = screen.getByRole('textbox', { name: 'Seria 1: Powt.' });
await user.clear(reps1);
await user.type(reps1, '8');
await user.click(screen.getByRole('button', { name: 'Dodaj serię' }));
expect(screen.getByRole('textbox', { name: 'Seria 2: Powt.' })).toHaveValue('8');
await user.click(screen.getByRole('button', { name: 'Dodaj serię' }));
expect(screen.getByRole('textbox', { name: 'Seria 3: Powt.' })).toHaveValue('8');
await user.click(screen.getByRole('button', { name: 'Usuń ostatnią serię' }));
expect(screen.queryByRole('textbox', { 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: „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: '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('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');
});
});