Files
FitOS/app/test/ProfileOverview.test.tsx

245 lines
9.0 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, 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';
// „Wczoraj" wg kalendarza lokalnego — wspólna podstawa mocków i oczekiwań,
// żeby toISOString() (UTC) nie rozmijało się z toLocaleDateString (lokalna)
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const YESTERDAY_ISO = `${yesterday.getFullYear()}-${String(yesterday.getMonth() + 1).padStart(2, '0')}-${String(
yesterday.getDate(),
).padStart(2, '0')}`;
const YESTERDAY_PL = yesterday.toLocaleDateString('pl-PL', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
});
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: 'chest',
exclusions: 'knee',
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-22T10:00:00.000Z',
};
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function mockApi() {
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/body-parameters'))
return jsonResponse(200, {
weight: [{ id: 'w-1', value: 82.5, date: '2026-08-15T08:00:00.000Z' }],
circumferences: [],
});
if (url.includes('/me/history'))
return jsonResponse(200, {
sessions: [
{
// bieżąca data (wczoraj) — wchodzi w „Objętość 7 dni”
id: 's-1',
status: 'COMPLETED',
startedAt: new Date(Date.now() - 86400000).toISOString(),
endedAt: new Date(Date.now() - 86400000 + 3600000).toISOString(),
date: YESTERDAY_ISO,
dayOfWeek: 1,
plan: 'Plan A',
exercises: [
{
id: 'e-1',
name: 'Przysiady',
muscle: 'legs',
isExtra: false,
comments: [],
sets: [
{
index: 0,
reps: 10,
rir: 2,
difficulty: null,
planned: { reps: 10, loadKg: 60, restSec: 90, rir: null },
},
],
},
],
},
{
id: 's-2',
status: 'COMPLETED',
startedAt: '2026-08-22T16:00:00.000Z',
endedAt: '2026-08-22T17:00:00.000Z',
date: '2026-08-22',
dayOfWeek: 6,
plan: 'Plan A',
exercises: [],
},
{
id: 's-3',
status: 'ABANDONED',
startedAt: '2026-08-20T16:00:00.000Z',
endedAt: null,
date: '2026-08-20',
dayOfWeek: 4,
plan: 'Plan A',
exercises: [],
},
],
});
if (url.includes('/gyms'))
return jsonResponse(200, {
gyms: [
{
id: 'g-1',
name: 'Żelazna Świątynia',
location: 'Warszawa',
availability: null,
capacity: null,
equipment: [],
roles: ['MEMBER'],
},
],
});
if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
if (url.includes('/dashboard'))
return jsonResponse(200, {
killstreak: 3,
activePlan: null,
nextTraining: null,
progress: null,
});
if (url.includes('/exercises')) return jsonResponse(200, { exercises: [] });
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' } });
}),
);
}
async function loginToProfile(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: 'Profil' }));
expect(await screen.findByRole('heading', { name: 'Profil' })).toBeInTheDocument();
}
function renderApp() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/profile']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('Profile overview — hero, statystyki i wiersze sekcji', () => {
it('renders hero, mini-stats and section rows with summaries', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await loginToProfile(user);
// hero: nazwa + e-mail
expect(screen.getByText('Jan Kowalski')).toBeInTheDocument();
expect(screen.getByText('jan@test.local')).toBeInTheDocument();
// pasek statystyk: killstreak, ostatnia waga, objętość 7 dni (60×10 z wczorajszej sesji), sesje
// (wartość killstreak w zakresie karty — „Sesje” też ma wartość 3)
const killStat = screen.getByText('Killstreak').closest('div.min-w-0') as HTMLElement;
expect(within(killStat).getByText('3')).toBeInTheDocument();
expect(screen.getByText('Ostatnia waga')).toBeInTheDocument();
expect(screen.getByText('82.5 kg')).toBeInTheDocument();
expect(screen.getByText('Objętość 7 dni')).toBeInTheDocument();
expect(screen.getByText('600 kg')).toBeInTheDocument();
expect(screen.getByText('Sesje')).toBeInTheDocument();
// dane osobowe: imię i nazwisko + wiek/wzrost
const infoRow = await screen.findByRole('link', { name: /Dane osobowe/ });
expect(infoRow).toHaveTextContent('Jan Kowalski');
expect(infoRow).toHaveTextContent('30 lat · 180 cm');
// parametry ciała: najnowsza waga z datą
const bpRow = screen.getByRole('link', { name: /Parametry ciała/ });
expect(bpRow).toHaveTextContent('82.5 kg · 15.08.2026');
// historia: liczba sesji (polska odmiana) + data ostatniej (wczoraj)
const histRow = screen.getByRole('link', { name: /Historia treningów/ });
const lastDate = YESTERDAY_PL;
expect(histRow).toHaveTextContent(`3 sesje · ostatnia ${lastDate}`);
// siłownie: nazwy (sidebar ma też link „Siłownie" — wiersz niesie nazwę siłowni)
const gymsRow = screen.getByRole('link', { name: /^Siłownie / });
expect(gymsRow).toHaveTextContent('Żelazna Świątynia');
});
it('section rows navigate to the subpage and back', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await loginToProfile(user);
await user.click(await screen.findByRole('link', { name: /Historia treningów/ }));
// wspólna nazwa sekcji: topbar (h1) = PageHeader (h2)
expect(
await screen.findByRole('heading', { name: 'Historia treningów', level: 1 }),
).toBeInTheDocument();
// pełna sekcja na podstronie (nagłówek sesji: data · plan)
const lastDate = YESTERDAY_PL;
expect(screen.getByText(`${lastDate} · Plan A`)).toBeInTheDocument();
// wstecz wraca na przegląd („Wstecz” jest w topmenu i w treści — oba prowadzą do /profile)
await user.click(screen.getAllByRole('button', { name: 'Wstecz' })[0]);
expect(await screen.findByRole('heading', { name: 'Profil' })).toBeInTheDocument();
expect(screen.getByRole('link', { name: /Dane osobowe/ })).toBeInTheDocument();
});
});