Files
FitOS/app/test/Plans.test.tsx

333 lines
12 KiB
TypeScript

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, Plan } 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',
};
const todayIso = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
d.getDate(),
).padStart(2, '0')}`;
};
const PLANS: Plan[] = [
{
id: 'plan-1',
userId: 'u1',
title: 'Plan masowy',
status: 'ACTIVE',
weeksCount: 8,
startDate: '2026-08-24',
progress: { completed: 5, total: 10, percent: 50 },
currentWeek: 2,
nextDay: { date: '2026-11-20', dayOfWeek: 5, exerciseCount: 4 },
weeks: [],
},
{
id: 'plan-2',
userId: 'u1',
title: 'Szkic siłowy',
status: 'DRAFT',
weeksCount: 4,
startDate: null,
weeks: [],
},
{
id: 'plan-3',
userId: 'u1',
title: 'Plan definicyjny',
status: 'COMPLETED',
weeksCount: 6,
startDate: '2026-06-01',
weeks: [],
},
];
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function mockApi(plans: Plan[] = PLANS) {
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes('/auth/login'))
return jsonResponse(200, { user: USER, accessToken: 'tok-1' });
if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
if (url.includes('/dashboard'))
return jsonResponse(200, {
killstreak: 0,
activePlan: null,
nextTraining: null,
progress: null,
});
if (url.includes('/exercises')) return jsonResponse(200, { exercises: [] });
if (url.includes('/plans/shared-with-me')) return jsonResponse(200, { plans: [] });
if (url.includes('/plans/shared-by-me')) return jsonResponse(200, { plans: [] });
if (url.includes('/plans/templates')) return jsonResponse(200, { templates: [] });
if (url.includes('/plans')) return jsonResponse(200, { plans });
if (url.includes('/calendar')) return jsonResponse(200, { month: '2026-08', days: [] });
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 openPlans(user: userEvent.User) {
expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument();
const email = document.querySelector('input[type="email"]') as HTMLInputElement;
const password = document.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(email, 'jan@test.local');
await user.type(password, 'Password123!');
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: 'Plany treningowe' }));
expect(await screen.findByRole('heading', { name: 'Plany treningowe' })).toBeInTheDocument();
}
/** Hub → kategoria „Aktualne” (podstrona z listą; powrót „Wstecz” w topbarze). */
async function openCurrentPlans(user: userEvent.User) {
await openPlans(user);
await user.click(await screen.findByRole('link', { name: /^Aktualne/ }));
expect(await screen.findByRole('button', { name: 'Wstecz' })).toBeInTheDocument();
}
beforeEach(() => {
setAccessToken(null);
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
useAuth.setState({ user: null, ready: false });
});
describe('Strona główna sekcji planów (/plans)', () => {
it('kafelki kategorii z licznikami prowadzą do podstron', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
const current = await screen.findByRole('link', { name: /^Aktualne/ });
expect(current).toHaveAttribute('href', '/plans/current');
expect(within(current).getByText(/1 aktywny · 1 szkic/)).toBeInTheDocument();
const archive = screen.getByRole('link', { name: /^Archiwum/ });
expect(within(archive).getByText('1 ukończony')).toBeInTheDocument();
const templates = screen.getByRole('link', { name: /^Szablony/ });
expect(within(templates).getByText('Brak szablonów')).toBeInTheDocument();
const shared = screen.getByRole('link', { name: /^Udostępnione/ });
expect(within(shared).getByText('Brak udostępnień')).toBeInTheDocument();
// płaska lista stanów zniknęła z indeksu — są tylko kafelki
expect(screen.queryByRole('link', { name: /Szkic siłowy/ })).not.toBeInTheDocument();
await user.click(archive);
expect(await screen.findByRole('heading', { name: 'Ukończony' })).toBeInTheDocument();
// brak paska zakładek — powrót do huba tylko przez „Wstecz” w topbarze
expect(screen.getByRole('button', { name: 'Wstecz' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Aktualne' })).not.toBeInTheDocument();
});
it('aktywny plan eksponowany jako hero także na stronie głównej', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
const hero = await screen.findByRole('link', { name: /Plan masowy/ });
expect(hero).toHaveAttribute('href', '/plans/plan-1');
expect(within(hero).getByText('Następny trening:')).toBeInTheDocument();
});
it('akcja „Nowy plan” dostępna też na stronie głównej', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
await user.click(await screen.findByRole('button', { name: 'Nowy plan' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Zacznij od zera albo skopiuj gotowy szablon.')).toBeInTheDocument();
});
});
describe('Podstrona „Aktualne” (/plans/current)', () => {
it('podstrona ma „Wstecz” w topbarze, który wraca do huba z kafelkami', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
await user.click(screen.getByRole('button', { name: 'Wstecz' }));
const templates = await screen.findByRole('link', { name: /^Szablony/ });
expect(templates).toHaveAttribute('href', '/plans/templates');
});
it('aktywny plan jest hero: postęp dni, „Tydzień X z Y”, następny trening', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
const hero = await screen.findByRole('link', { name: /Plan masowy/ });
expect(hero).toHaveAttribute('href', '/plans/plan-1');
expect(within(hero).getByText('Tydzień 2 z 8')).toBeInTheDocument();
expect(within(hero).getByText('5/10 dni')).toBeInTheDocument();
expect(within(hero).getByText('Następny trening:')).toBeInTheDocument();
// piątek, przyszła data + liczba ćwiczeń
expect(within(hero).getByText('Piątek · 20.11.2026')).toBeInTheDocument();
expect(within(hero).getByText('4 ćwiczenia')).toBeInTheDocument();
});
it('gdy następny trening wypada dziś — hero pokazuje etykietę „dziś”', async () => {
const withToday: Plan[] = [
{
...PLANS[0],
nextDay: { date: todayIso(), dayOfWeek: ((new Date().getDay() + 6) % 7) + 1, exerciseCount: 2 },
},
PLANS[1],
];
mockApi(withToday);
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
const hero = await screen.findByRole('link', { name: /Plan masowy/ });
expect(within(hero).getByText(/dziś/)).toBeInTheDocument();
});
it('bez planu ACTIVE — brak hero; archiwalne plany znikają z listy', async () => {
mockApi([PLANS[1], PLANS[2]]);
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
expect(screen.getByRole('link', { name: /Szkic siłowy/ })).toBeInTheDocument();
expect(screen.queryByText('Następny trening:')).not.toBeInTheDocument();
expect(screen.queryByText('Tydzień 2 z 8')).not.toBeInTheDocument();
// ukończony plan należy do archiwum, nie do „Aktualnych”
expect(screen.queryByRole('link', { name: /Plan definicyjny/ })).not.toBeInTheDocument();
});
it('archiwum: kafelek huba prowadzi do listy COMPLETED i ABANDONED', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
await user.click(await screen.findByRole('link', { name: /^Archiwum/ }));
expect(await screen.findByRole('heading', { name: 'Ukończony' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Plan definicyjny/ })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: /Plan masowy/ })).not.toBeInTheDocument();
});
it('każdy kafelek jest linkiem otwierającym szczegóły planu', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
const tile = await screen.findByRole('link', { name: /Szkic siłowy/ });
expect(tile).toHaveAttribute('href', '/plans/plan-2');
expect(tile).toHaveTextContent('Otwórz');
expect(tile).toHaveTextContent('4 tyg.');
});
it('pusty stan pokazuje komunikat i akcję „Nowy plan”', async () => {
mockApi([]);
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
expect(await screen.findByRole('heading', { name: 'Brak planów' })).toBeInTheDocument();
// akcja „Nowy plan”: topbar + pusty stan
expect(screen.getAllByRole('button', { name: 'Nowy plan' }).length).toBeGreaterThan(0);
});
it('„Nowy plan” otwiera wybór: od zera albo z szablonu', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
await user.click(await screen.findByRole('button', { name: 'Nowy plan' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText('Zacznij od zera albo skopiuj gotowy szablon.')).toBeInTheDocument();
await user.click(within(dialog).getByRole('button', { name: 'Od zera' }));
expect(await screen.findByRole('heading', { name: 'Nowy plan' })).toBeInTheDocument();
});
it('filtr statusu z menu kontekstowego pokazuje tylko daną kategorię', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
await user.click(await screen.findByRole('button', { name: /Status:/ }));
await user.click(await screen.findByRole('button', { name: 'Szkice' }));
// lista płaska wybranej kategorii: tylko szkic, hero aktywnego znika
expect(screen.getByRole('link', { name: /Szkic siłowy/ })).toBeInTheDocument();
expect(screen.queryByRole('link', { name: /Plan masowy/ })).not.toBeInTheDocument();
expect(screen.queryByText('Następny trening:')).not.toBeInTheDocument();
});
it('sortowanie nazwą A→Z porządkuje listę płaską (bez hero)', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openCurrentPlans(user);
await user.click(await screen.findByRole('button', { name: /Sortuj:/ }));
await user.click(await screen.findByRole('button', { name: 'Nazwa A→Z' }));
// sortowanie globalne = lista płaska: Plan masowy, Szkic siłowy (aktywny traci hero)
const tiles = Array.from(document.querySelectorAll('a[href^="/plans/plan-"]')).map((a) =>
a.getAttribute('href'),
);
expect(tiles).toEqual(['/plans/plan-1', '/plans/plan-2']);
expect(screen.getByRole('heading', { name: 'Wszystkie plany' })).toBeInTheDocument();
});
});