Files
FitOS/app/test/DayExecution.test.tsx

1161 lines
51 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';
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: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-22T10:00:00.000Z',
};
interface CatalogExercise {
id: string;
name: string;
primaryMuscle: string;
}
/** Katalog ćwiczeń dostępny w modalu „Dodaj ćwiczenie”. */
const CATALOG: CatalogExercise[] = [
{ id: 'pz-3', name: 'Martwy ciąg', primaryMuscle: 'back' },
{ id: 'pz-4', name: 'Wiosłowanie', primaryMuscle: 'back' },
];
/** Ciało GET /sessions/sess-1 — reps per serii (ss-1, ss-2 w ćwiczeniu planowym; ss-3 dodane).
* `indices` pozwala symulować luki w indeksach (np. po usunięciu serii).
* `extra` — ćwiczenia dodane do sesji (bez planu, puste serie). */
function sessionBody(
reps: Record<string, number | null>,
indices: Record<string, number> = {},
status: 'IN_PROGRESS' | 'ABANDONED' = 'IN_PROGRESS',
extra: CatalogExercise[] = [],
notes: Record<string, string | null> = {},
rirOnly: string[] = [],
addedSets: Record<string, number> = {},
noLoad = false,
) {
const has = (id: string) => reps[id] != null;
const secondary = (id: string) => has(id) || rirOnly.includes(id);
return {
session: {
id: 'sess-1',
status,
startedAt: '2026-08-24T07:00:00.000Z',
day: {
id: 'day-1',
date: '2026-08-24',
status: 'PLANNED',
week: { plan: { id: 'plan-1', title: 'Plan testowy', status: 'ACTIVE' } },
moveLog: [],
},
exercises: [
{
id: 'se-1',
order: 0,
hidden: false,
removed: false,
exercise: { id: 'pz-1', name: 'Przysiady', primaryMuscle: 'legs' },
planExercise: {
id: 'pe-1',
sets: [
{
id: 'ps-1',
index: 0,
reps: 10,
loadKg: noLoad ? null : 60,
restSec: 90,
rir: 2,
cardioBpm: null,
timeSec: null,
speed: null,
},
{
id: 'ps-2',
index: 1,
reps: 8,
loadKg: noLoad ? null : 60,
restSec: 90,
rir: 2,
cardioBpm: null,
timeSec: null,
speed: null,
},
],
},
sets: [
{
id: 'ss-1',
planSetId: 'ps-1',
index: indices['ss-1'] ?? 0,
reps: reps['ss-1'],
// pusta seria nie ma wpisanych rir/trudności (wtedy przycisk to „Uzupełnij serię”, nie „Edytuj”)
rir: secondary('ss-1') ? 2 : null,
difficulty: secondary('ss-1') ? 3 : null,
note: notes['ss-1'] ?? null,
},
{
id: 'ss-2',
planSetId: 'ps-2',
index: indices['ss-2'] ?? 1,
reps: reps['ss-2'],
rir: secondary('ss-2') ? 2 : null,
difficulty: secondary('ss-2') ? 3 : null,
note: notes['ss-2'] ?? null,
},
],
},
{
id: 'se-2',
order: 1,
hidden: false,
removed: false,
exercise: { id: 'pz-2', name: 'Wyciskanie', primaryMuscle: 'chest' },
planExercise: null,
sets: [
{
id: 'ss-3',
planSetId: null,
index: 0,
reps: reps['ss-3'],
rir: null,
difficulty: null,
note: notes['ss-3'] ?? null,
},
],
},
...extra.map((e, i) => ({
id: `se-x${i + 1}`,
order: 2 + i,
hidden: false,
removed: false,
exercise: { id: e.id, name: e.name, primaryMuscle: e.primaryMuscle },
planExercise: null,
// auto-seria po dodaniu ćwiczenia: POST /sessions/exercises/:id/sets dopisuje pending
sets: Array.from({ length: addedSets[e.id] ?? 0 }, (_, s) => ({
id: `ss-ax-${i + 1}-${s}`,
planSetId: null,
index: s,
reps: null,
rir: null,
difficulty: null,
note: null,
})),
})),
],
},
};
}
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
interface MockApiOptions {
/** Początkowy stan: sesja ABANDONED (np. po auto-porzuceniu przez scheduler). */
abandoned?: boolean;
/** Początkowy stan: sesja COMPLETED (dzień COMPLETED) — test „Wznów trening”. */
completed?: boolean;
/** Początkowy stan: dzień SKIPPED (domyślnie: jak `abandoned`). */
daySkipped?: boolean;
/** Dashboard zwraca nextTraining day-1 (przycisk „Wykonaj trening”). */
nextTraining?: boolean;
/** Katalog ćwiczeń w modalu „Dodaj ćwiczenie”. */
exerciseCatalog?: CatalogExercise[];
/** Serie z zapisanym samym RIR/trudnością (bez powtórzeń). */
rirOnly?: string[];
/** PATCH serii nigdy nie odpowiada (test startu odliczania przed odpowiedzią). */
hangSets?: boolean;
/** PATCH serii odpowiada 500 (test rollbacku optymistycznego timera). */
failSets?: boolean;
/** Serie z planu bez obciążenia (loadKg null) — trening z masą ciała. */
noLoad?: boolean;
/** Podsumowanie zwracane przez POST /sessions/sess-1/complete (null = serwer bez podsumowania). */
completionSummary?: unknown;
}
function mockApi(
reps: Record<string, number | null>,
indices: Record<string, number> = {},
opts: MockApiOptions = {},
) {
// Stateful: POST /sessions/sess-1/abandon oznacza sesję jako ABANDONED,
// a dzień jako SKIPPED (treningu nie da się ponownie wykonać).
let abandoned = opts.abandoned ?? false;
let completed = opts.completed ?? false;
let daySkipped = opts.daySkipped ?? abandoned;
const { nextTraining = false } = opts;
const catalog = opts.exerciseCatalog ?? CATALOG;
const rirOnly = opts.rirOnly ?? [];
// Stateful: POST /sessions/sess-1/exercises dodaje ćwiczenie do sesji (widoczne po refetchu).
const added: CatalogExercise[] = [];
// Stateful: auto-serie nowo dodanych ćwiczeń (POST /sessions/exercises/:id/sets).
const addedSets: Record<string, number> = {};
// Stateful: PATCH /sessions/sets/:id zapisuje komentarz serii (widoczny po refetchu).
const notes: Record<string, string | null> = {};
// Stateful: PATCH /sessions/sets/:id zapisuje powtórzenia (jak serwer) — po zapisie
// seria staje się uzupełniona, a „Następna” przesuwa się na kolejną pustą.
const repsState: Record<string, number | null> = { ...reps };
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: abandoned
? null
: {
id: 'sess-1',
dayId: 'day-1',
dayDate: '2026-08-24',
dayOfWeek: 1,
planTitle: 'Plan testowy',
startedAt: '2026-08-24T07:00:00.000Z',
},
});
if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
if (url.includes('/dashboard'))
return jsonResponse(200, {
killstreak: 0,
activePlan: null,
nextTraining: nextTraining
? {
dayId: 'day-1',
date: '2026-08-24',
exercises: [{ name: 'Przysiady', muscle: 'legs' }],
}
: null,
progress: null,
extra: null,
missing: null,
});
if (url.includes('/sessions/sess-1/abandon')) {
abandoned = true;
daySkipped = true;
return jsonResponse(200, { ok: true });
}
if (url.includes('/sessions/sess-1/complete') && method === 'POST') {
completed = true;
abandoned = false;
daySkipped = false;
return jsonResponse(200, { ok: true, summary: opts.completionSummary ?? null });
}
if (url.includes('/sessions/sess-1/reopen') && method === 'POST') {
if (!completed)
return jsonResponse(400, {
error: { code: 'BAD_REQUEST', message: 'Only a completed session can be reopened' },
});
completed = false;
return jsonResponse(200, { sessionId: 'sess-1', status: 'IN_PROGRESS' });
}
if (url.includes('/sessions/sess-1/exercises') && method === 'POST') {
const body = JSON.parse(String(init?.body)) as { exerciseId: string };
const ex = catalog.find((c) => c.id === body.exerciseId);
if (ex && !added.some((a) => a.id === ex.id)) added.push(ex);
// id wiersza sesji jak w fixture (se-x1, se-x2…) — front używa go do rozwinięcia akordeonu
return jsonResponse(200, { exerciseId: `se-x${added.length}` });
}
if (url.includes('/sessions/exercises/') && method === 'POST') {
// POST /sessions/exercises/se-x1/sets — auto-seria dla ćwiczenia dodanego do sesji
const exId = url.split('/sessions/exercises/')[1]?.split('/')[0] ?? '';
const cat = added[parseInt(exId.replace('se-x', ''), 10) - 1];
if (cat) addedSets[cat.id] = (addedSets[cat.id] ?? 0) + 1;
return jsonResponse(200, {
setId: `ss-ax-${exId}`,
index: (cat ? addedSets[cat.id] : 1) - 1,
});
}
if (url.includes('/days/day-1'))
return jsonResponse(200, {
day: {
id: 'day-1',
date: '2026-08-24',
status: completed ? 'COMPLETED' : daySkipped ? 'SKIPPED' : 'PLANNED',
dayOfWeek: 1,
planId: 'plan-1',
plan: { id: 'plan-1', gym: null },
sessions: [
{
id: 'sess-1',
status: completed ? 'COMPLETED' : abandoned ? 'ABANDONED' : 'IN_PROGRESS',
startedAt: '2026-08-24T07:00:00.000Z',
},
],
},
});
if (url.includes('/sessions/sess-1'))
return jsonResponse(
200,
sessionBody(
repsState,
indices,
completed ? 'COMPLETED' : abandoned ? 'ABANDONED' : 'IN_PROGRESS',
added,
notes,
rirOnly,
addedSets,
opts.noLoad ?? false,
),
);
if (url.includes('/sessions/sets/')) {
if (method === 'PATCH') {
if (opts.hangSets) return new Promise<Response>(() => undefined);
if (opts.failSets)
return jsonResponse(500, {
error: { code: 'SERVER_ERROR', message: 'awaria serwera' },
});
const body = JSON.parse(String(init?.body)) as {
reps?: number | null;
note?: string | null;
};
const setId = url.split('/').pop() ?? '';
notes[setId] = body.note ?? null;
if ('reps' in body) repsState[setId] = body.reps ?? null;
}
return jsonResponse(200, {});
}
if (url.includes('/exercises')) return jsonResponse(200, { exercises: catalog });
if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] });
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
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={['/']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
}
async function openActiveDay(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();
// link „Trening” w menu bocznym (aktywna sesja)
const sidebarLink = screen.getByRole('link', { name: 'Trening', exact: true });
await user.click(sidebarLink);
expect(
await screen.findByRole('heading', { name: 'Poniedziałek · 24.08.2026' }),
).toBeInTheDocument();
// pasek sesji: status + start + postęp normy
expect(await screen.findByText('W trakcie')).toBeInTheDocument();
}
/**
* „Norma spełniona” wypełnia powtórzenia/RIR i od razu otwiera suwak trudności —
* helper zatwierdza suwak („Wpisz”), żeby wrócić do okna serii przed „Zapisz”.
*/
async function fillNormAndConfirmSlider(user: userEvent.User) {
await user.click(screen.getByRole('button', { name: 'Norma spełniona' }));
await screen.findByRole('heading', { name: 'Trudność' });
await user.click(screen.getByRole('button', { name: 'Wpisz' }));
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
// timer przerwy przeżywa remont w sessionStorage — izolujemy testy
sessionStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('Masa ciała w planie (seria bez obciążenia)', () => {
it('wiersz normy serii bez obciążenia informuje, że to trening z masą ciała', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': null }, {}, { noLoad: true });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// norma: „masa ciała × 10 powt.” zamiast „60 kg × 10 powt.” (dwie serie z planu)
expect(await screen.findAllByText('masa ciała')).toHaveLength(2);
expect(
screen.getByText((_, el) => el?.textContent === 'masa ciała × 10 powt.'),
).toBeInTheDocument();
expect(screen.queryByText('60 kg')).not.toBeInTheDocument();
});
});
describe('Kolejka serii w sesji', () => {
it('blokuje ukończenie sesji, dopóki nie wszystkie serie normowe są zakończone', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// postęp normy w procentach: 1 z 2 serii normowych zakończona (ss-3 to bonus)
expect(await screen.findByText('50%')).toBeInTheDocument();
// „Następna” = pierwsza niezakończona seria (dokładnie jedna)
expect(screen.getAllByText('Następna')).toHaveLength(1);
// przycisk ukończenia zablokowany + podpowiedź z odmianą
const completeBtn = screen.getByRole('button', { name: 'Ukończ sesję' });
expect(completeBtn).toBeDisabled();
expect(screen.getByText(/została 1 seria/)).toBeInTheDocument();
// klik „Dodaj serię” przy niedokończonej normie => alert z przyczyną (norma przed limitem bonusu)
await user.click(screen.getByRole('button', { name: 'Dodaj serię' }));
expect(
await screen.findByText('Najpierw zapisz wszystkie serie normowe tego ćwiczenia'),
).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'OK' }));
expect(
screen.queryByText('Najpierw zapisz wszystkie serie normowe tego ćwiczenia'),
).not.toBeInTheDocument();
});
it('pokazuje alert z przyczyną, gdy w tym ćwiczeniu trwa niezapisana seria dodatkowa', async () => {
mockApi({ 'ss-1': 10, 'ss-2': 10, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// norma zrobiona (100%), ale ss-3 to bonus w toku => klik „Dodaj serię” daje alert
expect(await screen.findByText('100%')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Dodaj serię' }));
expect(
await screen.findByText('W tym ćwiczeniu jest już niezapisana seria — najpierw ją uzupełnij'),
).toBeInTheDocument();
expect(screen.getByRole('dialog', { name: /Nie można dodać serii/ })).toBeInTheDocument();
expect(
screen.queryByText('Najpierw zapisz wszystkie serie normowe tego ćwiczenia'),
).not.toBeInTheDocument();
});
it('ukończona sesja daje „Wznów trening” i po wznowieniu wraca do edycji', async () => {
mockApi({ 'ss-1': 10, 'ss-2': 10, 'ss-3': 5 }, {}, { completed: true });
const user = userEvent.setup();
renderApp();
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 screen.findByRole('heading', { name: 'Dashboard' });
await user.click(screen.getByRole('link', { name: 'Trening', exact: true }));
expect(await screen.findByText('Ukończona')).toBeInTheDocument();
// tryb tylko do odczytu: brak akcji sesji, jest za to wznowienie
expect(screen.queryByRole('button', { name: 'Ukończ sesję' })).not.toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Wznów trening' }));
await waitFor(() =>
expect(screen.getByText('Sesja wznowiona — możesz poprawić wyniki')).toBeInTheDocument(),
);
expect(await screen.findByText('W trakcie')).toBeInTheDocument();
expect(await screen.findByRole('button', { name: 'Ukończ sesję' })).toBeInTheDocument();
});
it('blokuje ukończenie sesji alertem, gdy trwa niezapisana seria bonusowa', async () => {
mockApi({ 'ss-1': 10, 'ss-2': 10, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// normy zrobione (100%) => przycisk aktywny, ale niewidoczny bonus w toku blokuje koniec
expect(await screen.findByText('100%')).toBeInTheDocument();
const completeBtn = screen.getByRole('button', { name: 'Ukończ sesję' });
expect(completeBtn).toBeEnabled();
await user.click(completeBtn);
expect(screen.getByRole('dialog', { name: /Nie można ukończyć sesji/ })).toBeInTheDocument();
expect(
screen.getByText(
'Masz niezapisane serie bonusowe (1) — najpierw uzupełnij je lub usuń, potem ukończ trening.',
),
).toBeInTheDocument();
});
it('po ukończeniu sesji pokazuje okno podsumowania: killstreak, liczby i porównania', async () => {
mockApi(
{ 'ss-1': 10, 'ss-2': 8, 'ss-3': 12 },
{},
{
completionSummary: {
durationSec: 3660,
exercises: 2,
sets: 3,
bonusSets: 1,
reps: 30,
tonnageKg: 1240,
killstreak: { current: 5, best: 5, newRecord: true, sampleSize: 12, beatCount: 9 },
volume: { ownAvgKg: 1000, ownAvgSessions: 4, globalAvgKg: 600, globalSample: 25 },
},
},
);
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
expect(await screen.findByText('100%')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Ukończ sesję' }));
const dialog = await screen.findByRole('dialog', { name: /Trening zaliczony/ });
// killstreak z rekordem (odmiana: 5 dni)
expect(within(dialog).getByText('5 dni')).toBeInTheDocument();
expect(within(dialog).getByText(/nowy rekord passy/)).toBeInTheDocument();
// kafelki: serie / powtórzenia / ćwiczenia / tonaż
expect(within(dialog).getByText('3 serii')).toBeInTheDocument();
expect(within(dialog).getByText('30')).toBeInTheDocument();
expect(within(dialog).getByText('2 ćwiczenia')).toBeInTheDocument();
expect(within(dialog).getByText('1,2 t')).toBeInTheDocument();
// abstrakcyjne porównania: kroki, centyl passy, tonaż vs średnie, bonus
expect(within(dialog).getByText(/≈ 30 kroków marszu/)).toBeInTheDocument();
expect(within(dialog).getByText(/lepsza niż u 9 z 12 trenujących/)).toBeInTheDocument();
expect(within(dialog).getByText(/o 24% powyżej Twojej średniej z 30 dni/)).toBeInTheDocument();
expect(
within(dialog).getByText(/Więcej niż średnia trenujących na FitOS \(600 kg/),
).toBeInTheDocument();
expect(within(dialog).getByText('+1 seria ponad plan — bonus doliczony.')).toBeInTheDocument();
// okno zastępuje toast — brak dublowania komunikatu
expect(screen.queryByText('Sesja ukończona')).not.toBeInTheDocument();
await user.click(within(dialog).getByRole('button', { name: 'OK' }));
expect(screen.queryByRole('dialog', { name: /Trening zaliczony/ })).not.toBeInTheDocument();
});
it('gdy serwer nie zwrócił podsumowania, ukończenie daje zwykły toast bez okna', async () => {
mockApi({ 'ss-1': 10, 'ss-2': 8, 'ss-3': 12 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
expect(await screen.findByText('100%')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Ukończ sesję' }));
expect(await screen.findByText('Sesja ukończona')).toBeInTheDocument();
expect(screen.queryByRole('dialog', { name: /Trening zaliczony/ })).not.toBeInTheDocument();
});
it('przewija widok do następnej serii do uzupełnienia (auto-nawigacja)', async () => {
const spy = vi.fn();
const orig = Element.prototype.scrollIntoView;
Element.prototype.scrollIntoView = spy;
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
try {
renderApp();
await openActiveDay(user);
// następna seria to ss-2 (w rozwiniętym automatycznie ćwiczeniu) — na nią scroll
await waitFor(() => expect(spy).toHaveBeenCalled());
expect(spy.mock.contexts).toContain(document.getElementById('set-ss-2'));
} finally {
Element.prototype.scrollIntoView = orig;
}
});
it('odblokowuje „Dodaj serię” dla ćwiczenia bez normy mimo niedokończonej normy innego ćwiczenia', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': 12 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// Przysiady (rozwinięte): własna norma niedokończona (ss-2) => klik daje alert z przyczyną
await user.click(screen.getByRole('button', { name: 'Dodaj serię' }));
expect(
await screen.findByText('Najpierw zapisz wszystkie serie normowe tego ćwiczenia'),
).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'OK' }));
// Wyciskanie (dodane do sesji) nie ma normy planowej => bonus dostępny mimo ss-2, bez alertu;
// oba akordeony mogą być otwarte jednocześnie (nie wykluczają się)
await user.click(screen.getByRole('button', { name: /Wyciskanie/ }));
expect(screen.getAllByRole('button', { name: 'Dodaj serię' })).toHaveLength(2);
await user.click(screen.getAllByRole('button', { name: 'Dodaj serię' })[1]);
expect(screen.queryByRole('dialog', { name: /Nie można dodać serii/ })).not.toBeInTheDocument();
});
it('po zakończeniu wszystkich serii normowych odblokowuje ukończenie sesji', async () => {
mockApi({ 'ss-1': 10, 'ss-2': 8, 'ss-3': 12 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
expect(await screen.findByText('100%')).toBeInTheDocument();
expect(screen.queryByText('Następna')).not.toBeInTheDocument();
const completeBtn = screen.getByRole('button', { name: 'Ukończ sesję' });
expect(completeBtn).toBeEnabled();
expect(screen.queryByText(/został/)).not.toBeInTheDocument();
});
it('pokazuje bonus i odblokowuje „Dodaj serię” po zrobieniu normy', async () => {
mockApi({ 'ss-1': 10, 'ss-2': 8, 'ss-3': 12 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// ss-3 to seria bonusowa (dodana ponad plan) z zapisanym wynikiem
expect(screen.getByText('+1 bonus')).toBeInTheDocument();
// Wyciskanie (ss-3) jest zwinięte — rozwiń je przez nagłówek (akordeon)
await user.click(screen.getByRole('button', { name: /Wyciskanie/ }));
expect(screen.getByText('bonus', { exact: true })).toBeInTheDocument();
// norma zrobiona + brak aktywnej nadmiarowej => „Dodaj serię” odblokowane
expect(screen.getAllByRole('button', { name: 'Dodaj serię' })[0]).toBeEnabled();
});
it('uzupełnia serię wsadowo przez okno „Edytuj serię”', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// pierwsza seria jest uzupełniona — przycisk „Edytuj” otwiera okno
await user.click(screen.getByRole('button', { name: 'Edytuj' }));
expect(await screen.findByRole('heading', { name: 'Edytuj serię 1' })).toBeInTheDocument();
// pole „Powtórzenia” otwiera klawiaturę numeryczną
await user.click(screen.getByRole('button', { name: /Powtórzenia/ }));
expect(screen.getByRole('heading', { name: 'Powtórzenia' })).toBeInTheDocument();
// wyczyść i wpisz 12 (klawiszami)
await user.click(screen.getByRole('button', { name: 'Wyczyść' }));
await user.click(screen.getByRole('button', { name: '1', exact: true }));
await user.click(screen.getByRole('button', { name: '2', exact: true }));
expect(screen.getByDisplayValue('12')).toBeInTheDocument();
// „Wpisz” zamyka klawiaturę (okno serii nadal otwarte)
await user.click(screen.getByRole('button', { name: 'Wpisz' }));
expect(screen.queryByRole('heading', { name: 'Powtórzenia' })).not.toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Edytuj serię 1' })).toBeInTheDocument();
// „Zapisz” zamyka okno
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(screen.queryByRole('heading', { name: 'Edytuj serię 1' })).not.toBeInTheDocument();
});
it('wpisuje wartość ręcznie w polu klawiatury numerycznej', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getByRole('button', { name: 'Edytuj' }));
await screen.findByRole('heading', { name: 'Edytuj serię 1' });
// pole „Powtórzenia” otwiera klawiaturę; ręczne wpisanie w polu
await user.click(screen.getByRole('button', { name: /Powtórzenia/ }));
const field = screen.getByDisplayValue('10');
await user.clear(field);
await user.type(field, '25');
expect(screen.getByDisplayValue('25')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Wpisz' }));
expect(screen.queryByRole('heading', { name: 'Powtórzenia' })).not.toBeInTheDocument();
});
it('ocena trudności przez suwak (łatwo → trudno)', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getByRole('button', { name: 'Edytuj' }));
await screen.findByRole('heading', { name: 'Edytuj serię 1' });
// pole „Trudność” otwiera suwak
await user.click(screen.getByRole('button', { name: /Trudność/ }));
expect(screen.getByRole('heading', { name: 'Trudność' })).toBeInTheDocument();
expect(screen.getByText('łatwo')).toBeInTheDocument();
expect(screen.getByText('trudno')).toBeInTheDocument();
expect(screen.getByRole('slider')).toBeInTheDocument();
// „Wpisz” zamyka suwak (okno serii nadal otwarte)
await user.click(screen.getByRole('button', { name: 'Wpisz' }));
expect(screen.queryByRole('heading', { name: 'Trudność' })).not.toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Edytuj serię 1' })).toBeInTheDocument();
});
it('przycisk „Norma spełniona” wypełnia wartości z planu', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': 5 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// otwórz okno drugiej serii (ss-2, norma: powt. 8, RIR 2)
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 2' });
// przycisk „Norma spełniona” jest widoczny (seria ma normę)
const normBtn = screen.getByRole('button', { name: 'Norma spełniona' });
expect(normBtn).toBeInTheDocument();
// kliknięcie wypełnia wartości z planu (powt. 8, RIR 2)
// i od razu otwiera suwak trudności — bez ręcznego przeklikiwania się do niego
await user.click(normBtn);
await screen.findByRole('heading', { name: 'Trudność' });
expect(screen.getByRole('slider', { name: 'Trudność (suwak)' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Wpisz' }));
expect(screen.getByRole('button', { name: /Powtórzenia/ })).toHaveTextContent('8');
expect(screen.getByRole('button', { name: /RIR/ })).toHaveTextContent('2');
});
it('seria bonusowa (bez normy) nie ma przycisku „Norma spełniona”', async () => {
// normy zapisane (ss-2 po normie) => następna i jedyna do uzupełnienia to bonus ss-3
mockApi({ 'ss-1': 10, 'ss-2': 8, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// Wyciskanie (se-2) rozwija się samo (ćwiczenie z następną serią) — ss-3 ma
// jedyny przycisk „Uzupełnij serię” w sesji
const fillBtns = screen.getAllByRole('button', { name: 'Uzupełnij serię' });
expect(fillBtns).toHaveLength(1);
await user.click(fillBtns[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
expect(screen.queryByRole('button', { name: 'Norma spełniona' })).not.toBeInTheDocument();
});
it('nie pokazuje „Uzupełnij serię” dla przyszłych pustych serii (tylko dla następnej)', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// ss-1 jako jedyna pusta seria dostaje akcję; ss-2 (też pusta, przyszła, ta sama
// rozwinięta akordeon) — bez przycisku
expect(screen.getByText('Seria 2')).toBeInTheDocument();
expect(screen.getAllByRole('button', { name: 'Uzupełnij serię' })).toHaveLength(1);
});
it('anulowanie okna „Edytuj serię” zamyka je bez zapisu', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': 5 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getByRole('button', { name: 'Edytuj' }));
await screen.findByRole('heading', { name: 'Edytuj serię 1' });
await user.click(screen.getByRole('button', { name: 'Anuluj' }));
expect(screen.queryByRole('heading', { name: 'Edytuj serię 1' })).not.toBeInTheDocument();
// sesja nadal aktywna — akcja „Ukończ sesję” jest w grupie „Akcje”
// (klik w treść strony zwinał domyślnie otwartą grupę)
await user.click(screen.getByRole('button', { name: 'Akcje' }));
expect(screen.getByRole('button', { name: 'Ukończ sesję' })).toBeInTheDocument();
});
it('startuje odliczanie przerwy po pierwszym uzupełnieniu serii', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': 5 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// timer nie jest widoczny przed zapisaniem serii
expect(screen.queryByRole('button', { name: 'Zakończ' })).not.toBeInTheDocument();
// ss-2 jest pusta — uzupełnij ją („Norma spełniona” wypełnia wartości) i zapisz
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 2' });
await fillNormAndConfirmSlider(user);
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
// odliczanie startuje: format mm:ss + przycisk „Zakończ”
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
expect(screen.getByText(/^\d+:\d{2}$/)).toBeInTheDocument();
});
it('pokazuje w oknie „Uzupełnij serię” timer trwającej przerwy z informacją o resecie', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': 5 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// uzupełnij ss-1 i zapisz — startuje odliczanie przerwy (90 s z planu)
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await fillNormAndConfirmSlider(user);
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
// mock utrzymuje zapis (jak serwer) — „Następna" przesuwa się na ss-2; jej okno
// pokazuje timer trwającej przerwy + informację o resecie (ma zaplanowaną przerwę)
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 2' });
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('przerwa')).toBeInTheDocument();
expect(within(dialog).getByText(/^\d+:\d{2}$/)).toBeInTheDocument();
expect(within(dialog).getByText(/zrestartuje odliczanie przerwy/)).toBeInTheDocument();
});
it('w oknie serii bonusowej pokazuje timer przerwy bez informacji o resecie', async () => {
// norma ss-2 już zapisana — po dojechaniu ss-1 następna (i jedyna do
// uzupełnienia) jest seria bonusowa ss-3
mockApi({ 'ss-1': null, 'ss-2': 8, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// uzupełnij ss-1 i zapisz — startuje odliczanie przerwy
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await fillNormAndConfirmSlider(user);
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
// ss-3 to bonus (bez zaplanowanej przerwy) — jej okno ma timer, ale bez resetu
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('przerwa')).toBeInTheDocument();
expect(within(dialog).queryByText(/zrestartuje odliczanie przerwy/)).not.toBeInTheDocument();
});
it('nie zeruje wpisywanych wartości w oknie serii, gdy trwa przerwa (re-render rodzica co sekundę)', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': 5 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// uzupełnij ss-1 i zapisz — startuje odliczanie przerwy (rodzic re-renderuje co sekundę)
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await fillNormAndConfirmSlider(user);
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
// mock utrzymuje zapis — otwiera się okno następnej serii (ss-2); wpisz powtórzenia
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 2' });
await user.click(screen.getByRole('button', { name: /Powtórzenia/ }));
await user.click(screen.getByRole('button', { name: '1', exact: true }));
await user.click(screen.getByRole('button', { name: '2', exact: true }));
await user.click(screen.getByRole('button', { name: 'Wpisz' }));
expect(screen.getByText('12')).toBeInTheDocument();
// odczekaj na kilka tyknięć timeru przerwy (re-render rodzica) — wartość musi zostać
await new Promise((r) => setTimeout(r, 2500));
expect(screen.getByText('12')).toBeInTheDocument();
});
it('zapisuje opcjonalny komentarz serii i pokazuje go po ponownym otwarciu okna', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': 5 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await fillNormAndConfirmSlider(user);
// „Norma spełniona” nie czyści komentarza
await user.type(
screen.getByRole('textbox', { name: 'Komentarz do serii' }),
'ostatnia seria ciężka',
);
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
// komentarz musi być widoczny też na wierszu serii (dowód zapisu), nie tylko w oknie
expect(await screen.findByText('ostatnia seria ciężka')).toBeInTheDocument();
// mock utrzymuje zapis (jak serwer) — ss-1 jest już uzupełniona, wracamy do niej
// przez „Edytuj”, by sprawdzić, że komentarz przeżył zapis
await user.click(screen.getByRole('button', { name: 'Edytuj' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByRole('textbox', { name: 'Komentarz do serii' })).toHaveValue(
'ostatnia seria ciężka',
);
});
it('nie pokazuje timera przerwy w oknie serii, gdy przerwa nie trwa', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': 5 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
const dialog = await screen.findByRole('dialog');
expect(within(dialog).queryByText('przerwa')).not.toBeInTheDocument();
});
it('nie startuje odliczania przy edycji już uzupełnionej serii', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// ss-1 jest już uzupełniona — edycja i zapis nie uruchamiają odliczania
await user.click(screen.getByRole('button', { name: 'Edytuj' }));
await screen.findByRole('heading', { name: 'Edytuj serię 1' });
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(screen.queryByRole('button', { name: 'Zakończ' })).not.toBeInTheDocument();
});
it('serii z samym RIR/trudnością (bez powtórzeń) nie traktuje jako uzupełnionej', async () => {
// kryterium „uzupełniona" musi być tożsame z serwerowym (completeSession liczy reps)
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': null }, {}, { rirOnly: ['ss-1'] });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// ss-1 ma zapisany RIR, ale brak powtórzeń — nadal „Uzupełnij serię”, nie „Edytuj”
expect(screen.queryByRole('button', { name: 'Edytuj' })).not.toBeInTheDocument();
expect(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]).toBeEnabled();
// norma liczona po powtórzeniach — żadna seria normowa nie jest zakończona
expect(await screen.findByText('0%')).toBeInTheDocument();
expect(screen.getByText(/zostały 2 serie/)).toBeInTheDocument();
// zapisany RIR/trudność pozostają widoczne w wierszu mimo braku powtórzeń
expect(screen.getByText('RIR 2 · Trudność 3')).toBeInTheDocument();
});
it('uruchamia odliczanie natychmiast przy kliknięciu „Zapisz”, przed odpowiedzią API', async () => {
// PATCH wisi w nieskończoność — timer nie może czekać na odpowiedź serwera
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': 5 }, {}, { hangSets: true });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await fillNormAndConfirmSlider(user);
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
// odliczanie widoczne mimo nierozstrzygniętego żądania
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
});
it('cofa odliczanie, gdy zapis serii kończy się błędem', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': 5 }, {}, { failSets: true });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await fillNormAndConfirmSlider(user);
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByText('awaria serwera')).toBeInTheDocument();
// timer wystartował optymistycznie, ale nieudany zapis musiał go cofnąć
expect(screen.queryByRole('button', { name: 'Zakończ' })).not.toBeInTheDocument();
});
it('odtwarza trwające odliczanie po opuszczeniu i powrocie na stronę dnia', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': 5 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
await fillNormAndConfirmSlider(user);
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
// nawigacja do dashboardu i z powrotem — komponent remountuje, odliczanie zostaje
await user.click(screen.getByRole('link', { name: 'Dashboard', exact: true }));
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Zakończ' })).not.toBeInTheDocument();
await user.click(screen.getByRole('link', { name: 'Trening', exact: true }));
expect(
await screen.findByRole('heading', { name: 'Poniedziałek · 24.08.2026' }),
).toBeInTheDocument();
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
});
it('numeruje serie sekwencyjnie (pozycja) mimo luk w indeksach po usunięciu', async () => {
// ss-2 ma indeks 2 ( luka po usuniętej serii ), ale powinna być „Seria 2” (pozycja)
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null }, { 'ss-2': 2 });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
expect(screen.getByText('Seria 2')).toBeInTheDocument();
expect(screen.queryByText('Seria 3')).not.toBeInTheDocument();
});
it('nie pokazuje „Usuń” dla ćwiczenia z planu, ale pokazuje dla dodanego ponad plan', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// Przysiady (se-1) to ćwiczenie z planu — brak przycisku „Usuń”
// Wyciskanie (se-2) to ćwiczenie dodane ponad plan — ma przycisk „Usuń”
const deleteButtons = screen.getAllByRole('button', { name: 'Usuń', exact: true });
expect(deleteButtons).toHaveLength(1);
});
});
describe('Dodawanie ćwiczenia do sesji', () => {
it('top menu „Dodaj ćwiczenie” otwiera modal, a wybór ćwiczenia dodaje je do sesji', async () => {
mockApi({ 'ss-1': 10, 'ss-2': 8, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// przycisk w top menu otwiera modal z listą ćwiczeń z katalogu (za ikoną ➕)
await user.click(screen.getByRole('button', { name: 'Dodawanie' }));
await user.click(screen.getByRole('button', { name: 'Dodaj ćwiczenie' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByRole('heading', { name: 'Dodaj ćwiczenie' })).toBeInTheDocument();
expect(within(dialog).getByText('Martwy ciąg')).toBeInTheDocument();
expect(within(dialog).getByText('Wiosłowanie')).toBeInTheDocument();
// wyszukiwarka odporna na diakrytyki: „ciag" znajdzie „Martwy ciąg", ukryje „Wiosłowanie"
const search = screen.getByPlaceholderText('Szukaj ćwiczenia…');
await user.type(search, 'ciag');
expect(within(dialog).getByText('Martwy ciąg')).toBeInTheDocument();
expect(within(dialog).queryByText('Wiosłowanie')).not.toBeInTheDocument();
// kategoria (partia mięśniowa) po wyczyszczeniu frazy pokazuje oba ćwiczenia
await user.clear(search);
await user.click(within(dialog).getByRole('button', { name: 'Plecy' }));
expect(within(dialog).getByText('Martwy ciąg')).toBeInTheDocument();
expect(within(dialog).getByText('Wiosłowanie')).toBeInTheDocument();
// wybór ćwiczenia dodaje je do sesji (bez planu) i zamyka modal
await user.click(within(dialog).getByRole('button', { name: /Martwy ciąg/ }));
expect(await screen.findByRole('heading', { name: 'Martwy ciąg' })).toBeInTheDocument();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
// dodane ćwiczenie rozwija się automatycznie — „Dodaj serię” od razu pod ręką
expect(screen.getByRole('button', { name: /Martwy ciąg/ })).toHaveAttribute(
'aria-expanded',
'true',
);
// otwarte akordeony: Wyciskanie (auto, następna seria) + Martwy ciąg => 2 przyciski
expect(screen.getAllByRole('button', { name: 'Dodaj serię' })).toHaveLength(2);
// akcja „Uzupełnij serię” tylko dla serii następnej (ss-3) — pusta auto-seria
// Martwego ciągu to przyszła seria, więc bez przycisku
expect(screen.getAllByRole('button', { name: 'Uzupełnij serię' })).toHaveLength(1);
});
it('pusty katalog ćwiczeń pokazuje komunikat w modalu', async () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null }, {}, { exerciseCatalog: [] });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// akcja „Dodaj ćwiczenie” jest za ikoną ➕ (grupa dodawania)
await user.click(screen.getByRole('button', { name: 'Dodawanie' }));
await user.click(screen.getByRole('button', { name: 'Dodaj ćwiczenie' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Brak ćwiczeń w katalogu.')).toBeInTheDocument();
});
});
describe('Porzucenie sesji', () => {
it('porzucona sesja blokuje ponowne wykonanie treningu (dzień pominięty)', async () => {
mockApi({ 'ss-1': null, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// przycisk „Porzuć sesję” w top menu otwiera okno potwierdzenia
await user.click(screen.getByRole('button', { name: 'Porzuć sesję' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByRole('heading', { name: 'Porzucić sesję?' })).toBeInTheDocument();
// potwierdzenie porzucenia
await user.click(within(dialog).getByRole('button', { name: 'Porzuć' }));
expect(await screen.findByText('Sesja porzucona')).toBeInTheDocument();
// sesja oznaczona jako porzucona — bez przycisków akcji
expect(await screen.findByText('Porzucona', { exact: true })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Ukończ sesję' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Porzuć sesję' })).not.toBeInTheDocument();
// dzień pominięty — brak przycisku „Rozpocznij sesję” (treningu nie da się ponownie wykonać)
expect(screen.queryByRole('button', { name: 'Rozpocznij sesję' })).not.toBeInTheDocument();
});
it('pokazuje „Rozpocznij sesję”, gdy dzień jest zaplanowany, a ostatnia sesja porzucona', async () => {
// np. po auto-porzuceniu sesji przez scheduler — dzień pozostaje PLANNED
mockApi(
{ 'ss-1': null, 'ss-2': null, 'ss-3': null },
{},
{ abandoned: true, daySkipped: false, nextTraining: true },
);
const user = userEvent.setup();
renderApp();
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();
// dashboard: „Wykonaj trening” prowadzi do dnia z porzuconą sesją
await user.click(screen.getByRole('button', { name: 'Wykonaj trening' }));
expect(
await screen.findByRole('heading', { name: 'Poniedziałek · 24.08.2026' }),
).toBeInTheDocument();
// porzucona sesja (read-only) + dzień zaplanowany => można rozpocząć nową sesję
expect(await screen.findByText('Porzucona', { exact: true })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Ukończ sesję' })).not.toBeInTheDocument();
expect(await screen.findByRole('button', { name: 'Rozpocznij sesję' })).toBeInTheDocument();
});
});
describe('Nawigacja „Wstecz” na stronie dnia', () => {
it('ukończony trening: przycisk „Wstecz” w treści prowadzi do planu dnia (/plans/:id)', async () => {
mockApi({ 'ss-1': 10, 'ss-2': 8, 'ss-3': 6 }, {}, { completed: true });
const user = userEvent.setup();
renderApp();
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 screen.findByRole('heading', { name: 'Dashboard' });
await user.click(screen.getByRole('link', { name: 'Trening', exact: true }));
expect(await screen.findByText('Ukończona')).toBeInTheDocument();
const back = await screen.findByRole('link', { name: 'Wstecz' });
expect(back).toHaveAttribute('href', '/plans/plan-1');
});
});