Files
FitOS/app/test/ProfileInfo.test.tsx

276 lines
11 KiB
TypeScript

import { render, screen, waitFor, 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',
nickname: null,
socialMedia: null,
age: 30,
heightCm: 180,
phone: '+48 600 000 000',
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: ['chest'],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: ['legs'],
createdAt: '2026-08-22T10:00:00.000Z',
};
const FOCUS_AREAS = [
{
id: 'fa-1',
name: 'Klatka piersiowa',
muscle: 'chest',
description: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'fa-2',
name: 'Nogi',
muscle: 'legs',
description: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'fa-3',
name: 'Grzbiet',
muscle: 'back',
description: null,
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
];
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
/** Mock stateful: PATCH /me łączy patch z użytkownikiem (jak w API). */
function mockApi() {
let meBody = { user: { ...USER }, memberships: [] };
const patches: Record<string, unknown>[] = [];
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: [], circumferences: [] });
if (url.includes('/me/history')) return jsonResponse(200, { sessions: [] });
if (url.includes('/me/focus-chain'))
return jsonResponse(200, { develop: [], canDo: [], difficult: [], avoid: [] });
if (url.includes('/me/exercise-progress')) return jsonResponse(200, { exercises: [] });
if (url.includes('/me') && method === 'PATCH') {
const patch = JSON.parse(String(init?.body)) as Record<string, unknown>;
patches.push(patch);
meBody = { ...meBody, user: { ...meBody.user, ...patch } };
return jsonResponse(200, meBody);
}
if (url.includes('/me')) return jsonResponse(200, meBody);
if (url.includes('/focus-areas')) return jsonResponse(200, { focusAreas: FOCUS_AREAS });
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 { patches };
}
async function loginToInfo(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();
await user.click(await screen.findByRole('link', { name: /Dane osobowe/ }));
expect(
await screen.findByRole('heading', { name: 'Dane osobowe', level: 2 }),
).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 — dane osobowe (karty per sekcja)', () => {
it('podgląd per sekcja + zapis podstawowych danych', async () => {
const { patches } = mockApi();
const user = userEvent.setup();
renderApp();
await loginToInfo(user);
// podgląd wierszami label→wartość (zakres: karta „Podstawowe dane” — sidebar też ma imię)
const basicCard = screen
.getByRole('heading', { name: 'Podstawowe dane' })
.closest('[data-slot="card"]') as HTMLElement;
expect(within(basicCard).getByText('Imię')).toBeInTheDocument();
expect(within(basicCard).getByText('Jan')).toBeInTheDocument();
expect(within(basicCard).getByText('Kowalski')).toBeInTheDocument();
expect(within(basicCard).getByText('30 lat')).toBeInTheDocument();
expect(within(basicCard).getByText('180 cm')).toBeInTheDocument();
expect(within(basicCard).getByText('+48 600 000 000')).toBeInTheDocument();
// edycje wyłącznie w menu kontekstowym (1 kontrolka = 1 miejsce)
expect(screen.queryAllByRole('button', { name: 'Edytuj' })).toHaveLength(0);
expect(screen.getByRole('button', { name: 'Edytuj dane' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Edytuj mięśnie' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Edytuj social' })).toBeInTheDocument();
// edycja podstawowych danych (akcja topbaru)
await user.click(screen.getByRole('button', { name: 'Edytuj dane' }));
const dialog = await screen.findByRole('dialog');
const firstName = within(dialog).getByDisplayValue('Jan');
await user.clear(firstName);
await user.type(firstName, 'Janusz');
await user.click(within(dialog).getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByText('Dane podstawowe zapisane')).toBeInTheDocument();
await waitFor(() =>
expect(patches).toEqual([
{
firstName: 'Janusz',
lastName: 'Kowalski',
nickname: null,
age: 30,
heightCm: 180,
phone: '+48 600 000 000',
availability: null,
},
]),
);
// podgląd zaktualizowany (mock /me jest stateful)
expect(screen.getByText('Janusz')).toBeInTheDocument();
});
it('edytor mięśni: zakładki, wyszukiwarka i konflikt rozwija↔unikać', async () => {
const { patches } = mockApi();
const user = userEvent.setup();
renderApp();
await loginToInfo(user);
// podgląd: 4 grupy badge'ów (Klatka piersiowa w „Co rozwija”, Nogi w „Co unikać”)
expect(screen.getByText('Klatka piersiowa')).toBeInTheDocument();
expect(screen.getByText('Nogi')).toBeInTheDocument();
// bottom sheet z zakładkami + wyszukiwarką (akcja topbaru)
await user.click(screen.getByRole('button', { name: 'Edytuj mięśnie' }));
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByRole('button', { name: 'Co rozwija' })).toBeInTheDocument();
expect(within(dialog).getByRole('button', { name: 'Co potrafi' })).toBeInTheDocument();
expect(within(dialog).getByRole('button', { name: 'Co trudne' })).toBeInTheDocument();
expect(within(dialog).getByRole('button', { name: 'Co unikać' })).toBeInTheDocument();
// wyszukiwarka filtruje chipy
const search = within(dialog).getByPlaceholderText('Szukaj mięśnia…');
await user.type(search, 'klat');
expect(within(dialog).getByRole('checkbox', { name: 'Klatka piersiowa' })).toBeInTheDocument();
expect(within(dialog).queryByRole('checkbox', { name: 'Nogi' })).not.toBeInTheDocument();
await user.clear(search);
// konflikt: wybór „Nogi” w „Co rozwija” wyklucza z „Co unikać” (między zakładkami)
await within(dialog).getByRole('checkbox', { name: 'Nogi' }).click();
await user.click(within(dialog).getByRole('button', { name: 'Co unikać' }));
expect(within(dialog).getByRole('checkbox', { name: 'Nogi' })).not.toHaveAttribute(
'aria-checked',
'true',
);
await user.click(within(dialog).getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByText('Priorytety i wykluczenia zapisane')).toBeInTheDocument();
await waitFor(() =>
expect(patches).toEqual([
{
developMuscles: ['chest', 'legs'],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
},
]),
);
// podgląd: Nogi tylko w „Co rozwija” (unikać puste)
expect(screen.getAllByText('Nogi').length).toBe(1);
});
it('zapis social media per sekcja', async () => {
const { patches } = mockApi();
const user = userEvent.setup();
renderApp();
await loginToInfo(user);
// akcja topbaru „Edytuj social”
await user.click(screen.getByRole('button', { name: 'Edytuj social' }));
const dialog = await screen.findByRole('dialog');
// nowy wpis: domyślna platforma + URL
await user.click(within(dialog).getByRole('button', { name: 'Dodaj social media' }));
await user.type(within(dialog).getByPlaceholderText('https://…'), 'https://instagram.com/jan');
await user.click(within(dialog).getByRole('button', { name: 'Zapisz' }));
expect(await screen.findByText('Social media zapisane')).toBeInTheDocument();
await waitFor(() =>
expect(patches).toEqual([
{ socialMedia: [{ platform: 'INSTAGRAM', url: 'https://instagram.com/jan' }] },
]),
);
// podgląd: klikalny link z nazwą platformy
const link = screen.getByRole('link', { name: 'Instagram' });
expect(link).toHaveAttribute('href', 'https://instagram.com/jan');
});
});