307 lines
13 KiB
TypeScript
307 lines
13 KiB
TypeScript
import { render, screen, waitFor } 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: null,
|
||
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(
|
||
circ: { id: string; name: string; value: number; date: string }[] = [
|
||
{ id: 'c-1', name: 'Biceps lewy', value: 38, date: '2026-08-01T08:00:00.000Z' },
|
||
],
|
||
) {
|
||
const weightState = [
|
||
{ id: 'w-1', value: 82.5, date: '2026-08-01T08:00:00.000Z' },
|
||
{ id: 'w-2', value: 81.8, date: '2026-08-15T08:00:00.000Z' },
|
||
];
|
||
const circState = [...circ];
|
||
const deleted: { kind: 'weight' | 'circumference'; id: string }[] = [];
|
||
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 (method === 'DELETE' && url.includes('/me/body-parameters/weight/')) {
|
||
const id = url.split('/').pop()!;
|
||
const idx = weightState.findIndex((w) => w.id === id);
|
||
if (idx < 0)
|
||
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
|
||
weightState.splice(idx, 1);
|
||
deleted.push({ kind: 'weight', id });
|
||
return new Response(null, { status: 204 });
|
||
}
|
||
if (method === 'DELETE' && url.includes('/me/body-parameters/circumference/')) {
|
||
const id = url.split('/').pop()!;
|
||
const idx = circState.findIndex((c) => c.id === id);
|
||
if (idx < 0)
|
||
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
|
||
circState.splice(idx, 1);
|
||
deleted.push({ kind: 'circumference', id });
|
||
return new Response(null, { status: 204 });
|
||
}
|
||
if (url.includes('/me/body-parameters')) {
|
||
const byName = new Map<
|
||
string,
|
||
{ name: string; points: { id: string; value: number; date: string }[] }
|
||
>();
|
||
for (const c of circState) {
|
||
const entry = byName.get(c.name) ?? { name: c.name, points: [] };
|
||
entry.points.push({ id: c.id, value: c.value, date: c.date });
|
||
byName.set(c.name, entry);
|
||
}
|
||
return jsonResponse(200, { weight: weightState, circumferences: [...byName.values()] });
|
||
}
|
||
if (url.includes('/me/history')) return jsonResponse(200, { sessions: [] });
|
||
if (url.includes('/me/focus-chain'))
|
||
return jsonResponse(200, { priorities: [], exclusions: [] });
|
||
if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
|
||
if (url.includes('/focus-areas')) return jsonResponse(200, { focusAreas: [] });
|
||
if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] });
|
||
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')) 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' } });
|
||
}),
|
||
);
|
||
return { deleted };
|
||
}
|
||
|
||
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();
|
||
// body parameters live on their own subpage — open it via the tile
|
||
await user.click(await screen.findByRole('link', { name: /Parametry ciała/ }));
|
||
// wspólna nazwa sekcji: topbar (h1) = PageHeader (h2)
|
||
expect(
|
||
await screen.findByRole('heading', { name: 'Parametry ciała', level: 1 }),
|
||
).toBeInTheDocument();
|
||
}
|
||
|
||
/** Klik w zakładkę części ciała (sama nazwa — wartości są w panelu). */
|
||
function selectPart(part: string) {
|
||
return screen.getByRole('button', { name: new RegExp(`^${part}$`) });
|
||
}
|
||
|
||
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 — body parameter removal', () => {
|
||
it('lists measurements with a delete button', async () => {
|
||
mockApi();
|
||
const user = userEvent.setup();
|
||
renderApp();
|
||
await loginToProfile(user);
|
||
|
||
// domyślnie wybrana „Waga": pełna historia pomiarów z przyciskami usuwania
|
||
expect(await screen.findByText('82.5 kg')).toBeInTheDocument();
|
||
// 81.8 kg: nagłówek panelu (ostatni pomiar) + wiersz listy
|
||
expect(screen.getAllByText('81.8 kg').length).toBe(2);
|
||
expect(screen.getAllByRole('button', { name: /Usuń pomiar wagi/ }).length).toBe(2);
|
||
|
||
// obwody żyją w panelu swojej części — otwieranym z paska kaflów
|
||
await user.click(selectPart('Biceps'));
|
||
// 38 cm: nagłówek panelu (ostatni pomiar) + wiersz listy
|
||
expect(screen.getAllByText('38 cm').length).toBe(2);
|
||
expect(screen.getByRole('button', { name: /Usuń pomiar Biceps lewy/ })).toBeInTheDocument();
|
||
});
|
||
|
||
it('deletes a weight measurement after confirmation', async () => {
|
||
const { deleted } = mockApi();
|
||
const user = userEvent.setup();
|
||
renderApp();
|
||
await loginToProfile(user);
|
||
|
||
await screen.findByText('82.5 kg');
|
||
// usuwamy najnowszy pomiar (15.08.2026)
|
||
await user.click(screen.getByRole('button', { name: /Usuń pomiar wagi z 15\.08\.2026/ }));
|
||
// dialog potwierdzenia
|
||
expect(await screen.findByRole('dialog')).toBeInTheDocument();
|
||
expect(screen.getByText('Usunąć pomiar?')).toBeInTheDocument();
|
||
await user.click(screen.getByRole('button', { name: 'Usuń' }));
|
||
|
||
expect(await screen.findByText('Pomiar usunięty')).toBeInTheDocument();
|
||
await waitFor(() => expect(deleted).toEqual([{ kind: 'weight', id: 'w-2' }]));
|
||
// po refetchu pomiar znika z listy
|
||
await waitFor(() => expect(screen.queryByText('81.8 kg')).not.toBeInTheDocument());
|
||
});
|
||
|
||
it('groups sided measurements by body part with a per-side legend', async () => {
|
||
mockApi([
|
||
{ id: 'c-1', name: 'Biceps lewy', value: 38, date: '2026-08-01T08:00:00.000Z' },
|
||
{ id: 'c-2', name: 'Biceps lewy', value: 39, date: '2026-08-15T08:00:00.000Z' },
|
||
{ id: 'c-3', name: 'Biceps prawy', value: 37, date: '2026-08-01T08:00:00.000Z' },
|
||
{ id: 'c-4', name: 'Biceps prawy', value: 38, date: '2026-08-15T08:00:00.000Z' },
|
||
// starszy pomiar swobodnym tekstem z literówką — wykrywany jako Biceps
|
||
{ id: 'c-5', name: 'Bicepcs', value: 40, date: '2026-08-20T08:00:00.000Z' },
|
||
{ id: 'c-6', name: 'Talia', value: 80, date: '2026-08-01T08:00:00.000Z' },
|
||
]);
|
||
const user = userEvent.setup();
|
||
renderApp();
|
||
await loginToProfile(user);
|
||
|
||
// pasek kaflów: `Bicepcs` scalony z grupą Biceps — nie ma osobnego kafla
|
||
await user.click(selectPart('Biceps'));
|
||
expect(screen.queryByText('Bicepcs')).not.toBeInTheDocument();
|
||
// nagłówek panelu: najnowszy pomiar grupy (40 cm, 20.08)
|
||
expect(screen.getAllByText('40 cm').length).toBe(2); // nagłówek + wiersz listy
|
||
// legenda obu stron przy wykresie
|
||
expect(screen.getByText('Lewy')).toBeInTheDocument();
|
||
expect(screen.getByText('Prawy')).toBeInTheDocument();
|
||
// wiersze listy z oznaczeniem strony
|
||
expect(screen.getByText('15.08.2026 · Lewy')).toBeInTheDocument();
|
||
expect(screen.getByText('15.08.2026 · Prawy')).toBeInTheDocument();
|
||
// talia to osobna grupa — własny kafel i panel
|
||
await user.click(selectPart('Talia'));
|
||
expect(screen.getAllByText('80 cm').length).toBe(2); // nagłówek panelu + wiersz
|
||
});
|
||
|
||
it('rozbija strony na osobne wykresy (lewy pierwszy), bez podwójnych dat na osi', async () => {
|
||
mockApi([
|
||
// dwa prawe i jedno lewe z TEJ SAMEJ daty — strony rysowane osobno,
|
||
// dni łączone w pojedyncze kategorie osi (bez dublujących się etykiet)
|
||
{ id: 'c-1', name: 'Udo prawy', value: 55, date: '2026-08-10T08:00:00.000Z' },
|
||
{ id: 'c-2', name: 'Udo prawy', value: 56, date: '2026-08-12T19:00:00.000Z' },
|
||
{ id: 'c-3', name: 'Udo lewy', value: 54, date: '2026-08-10T12:00:00.000Z' },
|
||
]);
|
||
const user = userEvent.setup();
|
||
renderApp();
|
||
await loginToProfile(user);
|
||
|
||
await user.click(selectPart('Udo'));
|
||
// nagłówek panelu (ostatni 56) + wiersz listy
|
||
expect((await screen.findAllByText('56 cm')).length).toBeGreaterThanOrEqual(2);
|
||
// dwa podpisyane wykresy: lewy zawsze przed prawym
|
||
const lewy = screen.getByText('Lewe');
|
||
const prawy = screen.getByText('Prawe');
|
||
expect(lewy.compareDocumentPosition(prawy) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||
// strona z jednym pomiarem uczciwie sygnalizuje za mało danych
|
||
expect(screen.getByText(/Za mało danych na wykres/)).toBeInTheDocument();
|
||
});
|
||
|
||
it('opens the add-measurement modal from the context menu', async () => {
|
||
mockApi();
|
||
const user = userEvent.setup();
|
||
renderApp();
|
||
await loginToProfile(user);
|
||
|
||
// formularze nie są inline — otwiera je przycisk w menu kontekstowym (za ikoną ➕)
|
||
expect(screen.queryByPlaceholderText('waga (kg)')).not.toBeInTheDocument();
|
||
await user.click(screen.getByRole('button', { name: 'Dodawanie' }));
|
||
await user.click(screen.getByRole('button', { name: 'Dodaj pomiar' }));
|
||
expect(await screen.findByRole('dialog')).toBeInTheDocument();
|
||
|
||
// zakładka Waga: wartość + data (pusta = dziś)
|
||
expect(screen.getByPlaceholderText('waga (kg)')).toBeInTheDocument();
|
||
expect(screen.getByLabelText('Data wagi')).toBeInTheDocument();
|
||
// zakładka Obwód: lista typów + wartość
|
||
await user.click(screen.getByRole('button', { name: 'Obwód' }));
|
||
expect(screen.getByRole('option', { name: 'Talia' })).toBeInTheDocument();
|
||
expect(screen.getByPlaceholderText('wartość (cm)')).toBeInTheDocument();
|
||
});
|
||
|
||
it('shows the weight delta vs previous measurement; adding lives only in the top menu', async () => {
|
||
mockApi();
|
||
const user = userEvent.setup();
|
||
renderApp();
|
||
await loginToProfile(user);
|
||
|
||
// postęp: 81.8 (15.08) − 82.5 (01.08) = −0,7 kg (spadek) — liczony z pełnej historii
|
||
expect(await screen.findByText('82.5 kg')).toBeInTheDocument();
|
||
expect(screen.getByText('−0,7 kg od pierwszego')).toBeInTheDocument();
|
||
|
||
// 1 kontrolka = 1 miejsce: w treści brak przycisków dodawania — dodaje się z topmenu
|
||
expect(screen.queryByRole('button', { name: /Dodaj wagę/ })).not.toBeInTheDocument();
|
||
|
||
await user.click(screen.getByRole('button', { name: 'Dodaj pomiar' }));
|
||
expect(await screen.findByRole('dialog')).toBeInTheDocument();
|
||
expect(screen.getByPlaceholderText('waga (kg)')).toBeInTheDocument();
|
||
});
|
||
|
||
it('shows all measurements from every month (chart covers the full history)', async () => {
|
||
mockApi([
|
||
{ id: 'c-1', name: 'Talia', value: 80, date: '2026-07-10T08:00:00.000Z' },
|
||
{ id: 'c-2', name: 'Talia', value: 82, date: '2026-08-10T08:00:00.000Z' },
|
||
]);
|
||
const user = userEvent.setup();
|
||
renderApp();
|
||
await loginToProfile(user);
|
||
|
||
// pomiary spoza bieżącego miesiąca są widoczne bez żadnego filtra
|
||
expect(await screen.findByText('82.5 kg')).toBeInTheDocument();
|
||
await user.click(selectPart('Talia'));
|
||
expect(screen.getByText('10.07.2026')).toBeInTheDocument();
|
||
// 10.08 w nagłówku panelu i w wierszu listy (zakładka pokazuje samą wartość)
|
||
expect(screen.getAllByText('10.08.2026').length).toBe(2);
|
||
// postęp Talii: 82 (10.08) − 80 (10.07) = +2 cm
|
||
expect(screen.getByText('+2 cm od pierwszego')).toBeInTheDocument();
|
||
});
|
||
});
|