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

190 lines
6.8 KiB
TypeScript

import { render, screen } 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: '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: [
{
id: 's-1',
status: 'COMPLETED',
startedAt: '2026-08-24T16:00:00.000Z',
endedAt: '2026-08-24T17:00:00.000Z',
date: '2026-08-24',
dayOfWeek: 1,
plan: 'Plan A',
exercises: [],
},
{
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: 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' } });
}),
);
}
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 — tiles', () => {
it('renders tiles with summary info for each section', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await loginToProfile(user);
// dane osobowe: imię i nazwisko + wiek/wzrost
const infoTile = await screen.findByRole('link', { name: /Dane osobowe/ });
expect(infoTile).toHaveTextContent('Jan Kowalski');
expect(infoTile).toHaveTextContent('30 lat · 180 cm');
// parametry ciała: najnowsza waga z datą
const bpTile = screen.getByRole('link', { name: /Parametry ciała/ });
expect(bpTile).toHaveTextContent('82.5 kg · 15.08.2026');
// historia: liczba sesji (polska odmiana) + data ostatniej
const histTile = screen.getByRole('link', { name: /Historia treningów/ });
expect(histTile).toHaveTextContent('3 sesje · ostatnia 24.08.2026');
// siłownie: nazwy (sidebar ma też link „Siłownie" — kafelek niesie nazwę siłowni)
const gymsTile = screen.getByRole('link', { name: /^Siłownie / });
expect(gymsTile).toHaveTextContent('Żelazna Świątynia');
});
it('tiles navigate to the section subpage and back', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await loginToProfile(user);
await user.click(await screen.findByRole('link', { name: /Historia treningów/ }));
// tytuł podstrony jest tylko w topmenu (nagłówek Layout)
expect(await screen.findByRole('heading', { name: 'Profil — historia' })).toBeInTheDocument();
// pełna sekcja na podstronie (wiersz: data · plan)
expect(screen.getByText('24.08.2026 · Plan A')).toBeInTheDocument();
// wstecz wraca na przegląd z kafelkami („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();
});
});