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

683 lines
30 KiB
TypeScript
Raw Normal View History

import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import App from '../src/App';
import { useAuth } from '../src/store/auth';
import { setAccessToken } from '../src/api/client';
import type { User } from '../src/api/types';
const USER: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
age: 30,
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> = {},
) {
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: 60, restSec: 90, rir: 2, cardioBpm: null, timeSec: null, speed: null },
{ id: 'ps-2', index: 1, reps: 8, loadKg: 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: reps['ss-1'] != null ? 2 : null,
difficulty: reps['ss-1'] != null ? 3 : null,
note: notes['ss-1'] ?? null,
},
{ id: 'ss-2', planSetId: 'ps-2', index: indices['ss-2'] ?? 1, reps: reps['ss-2'], rir: null, difficulty: 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,
sets: [],
})),
],
},
};
}
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: 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[];
}
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 daySkipped = opts.daySkipped ?? abandoned;
const { nextTraining = false } = opts;
const catalog = opts.exerciseCatalog ?? CATALOG;
// Stateful: POST /sessions/sess-1/exercises dodaje ćwiczenie do sesji (widoczne po refetchu).
const added: CatalogExercise[] = [];
// Stateful: PATCH /sessions/sets/:id zapisuje komentarz serii (widoczny po refetchu).
const notes: Record<string, string | null> = {};
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/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);
return jsonResponse(200, { exerciseId: body.exerciseId });
}
if (url.includes('/days/day-1'))
return jsonResponse(200, {
day: {
id: 'day-1',
date: '2026-08-24',
status: daySkipped ? 'SKIPPED' : 'PLANNED',
dayOfWeek: 1,
sessions: [
{ id: 'sess-1', status: abandoned ? 'ABANDONED' : 'IN_PROGRESS', startedAt: '2026-08-24T07:00:00.000Z' },
],
},
});
if (url.includes('/sessions/sess-1'))
return jsonResponse(200, sessionBody(reps, indices, abandoned ? 'ABANDONED' : 'IN_PROGRESS', added, notes));
if (url.includes('/sessions/sets/')) {
if (method === 'PATCH') {
const body = JSON.parse(String(init?.body)) as { note?: string | null };
const setId = url.split('/').pop() ?? '';
notes[setId] = body.note ?? 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();
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
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();
// „Dodaj serię” zablokowany, dopóki norma nie jest zrobiona
expect(screen.getAllByRole('button', { name: 'Dodaj serię' })[0]).toBeDisabled();
});
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': null });
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)
await user.click(normBtn);
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 () => {
mockApi({ 'ss-1': 10, 'ss-2': null, 'ss-3': null });
const user = userEvent.setup();
renderApp();
await openActiveDay(user);
// trzecia seria (ss-3) to bonus (bez planExercise) — rozwijamy Wyciskanie (akordeon:
// zwija się Przysiady), więc jej przycisk „Uzupełnij serię” jest jedynym widocznym
await user.click(screen.getByRole('button', { name: /Wyciskanie/ }));
await user.click(screen.getByRole('button', { name: 'Uzupełnij serię' }));
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
expect(screen.queryByRole('button', { name: 'Norma spełniona' })).not.toBeInTheDocument();
});
it('anulowanie okna „Edytuj serię” zamyka je bez zapisu', 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' });
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': null });
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 user.click(screen.getByRole('button', { name: 'Norma spełniona' }));
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': null });
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 user.click(screen.getByRole('button', { name: 'Norma spełniona' }));
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
// otwórz okno niezapisanej serii z zaplanowaną przerwą (mock nie utrzymuje zapisu,
// więc ss-1 nadal jest pusta) — timer + informacja o resecie
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
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 () => {
mockApi({ 'ss-1': null, 'ss-2': null, '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 user.click(screen.getByRole('button', { name: 'Norma spełniona' }));
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
// ss-3 to bonus (bez zaplanowanej przerwy) — rozwijamy Wyciskanie i otwieramy okno
await user.click(screen.getByRole('button', { name: /Wyciskanie/ }));
await user.click(screen.getByRole('button', { name: 'Uzupełnij serię' }));
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': null });
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 user.click(screen.getByRole('button', { name: 'Norma spełniona' }));
await user.click(screen.getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByRole('button', { name: 'Zakończ' })).toBeInTheDocument();
// otwórz ponownie okno ss-1 (mock nie utrzymuje zapisu) i wpisz powtórzenia klawiaturą
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
await screen.findByRole('heading', { name: 'Uzupełnij serię 1' });
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': null });
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 user.click(screen.getByRole('button', { name: 'Norma spełniona' }));
// „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' }));
// mock nie utrzymuje reps (seria nadal pusta) — ponowne otwarcie okna ss-1
await user.click(screen.getAllByRole('button', { name: 'Uzupełnij serię' })[0]);
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': null });
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('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();
// 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();
});
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();
});
});