328 lines
13 KiB
TypeScript
328 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',
|
||
};
|
||
|
||
const TEST_EQUIPMENT = [
|
||
{ id: 'eq-1', name: 'sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: null },
|
||
{ id: 'eq-2', name: 'hantle', kind: 'DUMBBELL', spec: { minKg: 2.5, maxKg: 25 }, description: null },
|
||
{ id: 'eq-3', name: 'Kettlebell', kind: 'KETTLEBELL', spec: { minKg: 4, maxKg: 32 }, description: null },
|
||
];
|
||
|
||
const MY_GYM = {
|
||
id: 'gym-1',
|
||
name: 'Żelazna Świątynia',
|
||
location: 'Warszawa',
|
||
availability: [{ start: '06:00', end: '22:00' }, null, null, null, null, null, null],
|
||
capacity: 50,
|
||
equipment: [
|
||
{ id: 'ge-1', gymId: 'gym-1', equipmentId: 'eq-1', quantity: 1, equipment: TEST_EQUIPMENT[0] },
|
||
{ id: 'ge-2', gymId: 'gym-1', equipmentId: 'eq-2', quantity: 2, equipment: TEST_EQUIPMENT[1] },
|
||
],
|
||
roles: ['OWNER', 'TRAINER'],
|
||
};
|
||
|
||
const OTHER_GYM = {
|
||
id: 'gym-2',
|
||
name: 'Mega Gym',
|
||
location: 'Kraków',
|
||
availability: null,
|
||
capacity: null,
|
||
equipment: [],
|
||
};
|
||
|
||
function jsonResponse(status: number, body: unknown) {
|
||
return new Response(JSON.stringify(body), {
|
||
status,
|
||
headers: { 'Content-Type': 'application/json' },
|
||
});
|
||
}
|
||
|
||
type GymEquipmentLink = {
|
||
id: string;
|
||
gymId: string;
|
||
equipmentId: string;
|
||
quantity: number;
|
||
equipment: (typeof TEST_EQUIPMENT)[number];
|
||
};
|
||
|
||
function mockApi(opts: { isAdmin?: boolean } = {}) {
|
||
const user: User = { ...USER, isAdmin: opts.isAdmin ?? false };
|
||
// Stateful gym list: equipment added via POST /gyms/:id/equipment appears on refetch.
|
||
const gymsState: { id: string; name: string; location: string | null; availability: unknown; capacity: number | null; equipment: GymEquipmentLink[]; roles: string[] }[] = [
|
||
{ ...MY_GYM, equipment: [...MY_GYM.equipment] },
|
||
];
|
||
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, 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'))
|
||
return jsonResponse(200, {
|
||
user,
|
||
memberships: [{ gymId: gymsState[0].id, roles: ['OWNER', 'TRAINER'], gym: gymsState[0] }],
|
||
});
|
||
if (method === 'GET' && url.endsWith('/equipment'))
|
||
return jsonResponse(200, { equipment: TEST_EQUIPMENT });
|
||
if (url.includes('/gyms')) {
|
||
if (method === 'PATCH' && url.includes('/equipment')) {
|
||
const body = JSON.parse(String(init?.body)) as { quantity: number };
|
||
const eqId = url.match(/equipment\/([^/]+)$/)?.[1];
|
||
gymsState[0] = {
|
||
...gymsState[0],
|
||
equipment: gymsState[0].equipment.map((l) =>
|
||
l.equipmentId === eqId ? { ...l, quantity: body.quantity } : l,
|
||
),
|
||
};
|
||
return jsonResponse(200, { gym: gymsState[0] });
|
||
}
|
||
if (method === 'POST' && url.includes('/equipment')) {
|
||
const body = JSON.parse(String(init?.body)) as { equipmentId: string; quantity?: number };
|
||
if (gymsState[0].equipment.some((l) => l.equipmentId === body.equipmentId)) {
|
||
return jsonResponse(409, {
|
||
error: { code: 'CONFLICT', message: 'Equipment already exists' },
|
||
});
|
||
}
|
||
const eq = TEST_EQUIPMENT.find((e) => e.id === body.equipmentId);
|
||
const link: GymEquipmentLink = {
|
||
id: `ge-${body.equipmentId}`,
|
||
gymId: gymsState[0].id,
|
||
equipmentId: body.equipmentId,
|
||
quantity: body.quantity ?? 1,
|
||
equipment: eq,
|
||
};
|
||
gymsState[0] = { ...gymsState[0], equipment: [...gymsState[0].equipment, link] };
|
||
return jsonResponse(200, { gym: gymsState[0] });
|
||
}
|
||
if (method === 'DELETE' && url.includes('/equipment')) return jsonResponse(204, {});
|
||
if (method === 'POST' && url.includes('/join'))
|
||
return jsonResponse(201, { membership: { gymId: OTHER_GYM.id, roles: ['MEMBER'] } });
|
||
if (method === 'POST' && url.endsWith('/gyms'))
|
||
return jsonResponse(201, { gym: { ...OTHER_GYM, roles: ['OWNER'] } });
|
||
if (url.includes('/gyms/all'))
|
||
return jsonResponse(200, { gyms: [...gymsState, OTHER_GYM] });
|
||
return jsonResponse(200, { gyms: gymsState });
|
||
}
|
||
if (url.includes('/dashboard'))
|
||
return jsonResponse(200, {
|
||
killstreak: 0,
|
||
activePlan: null,
|
||
nextTraining: null,
|
||
progress: null,
|
||
extra: null,
|
||
missing: 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) {
|
||
// not logged in -> redirected to /login
|
||
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();
|
||
// gyms section lives on its own subpage — open it via the tile
|
||
// (the sidebar also has a „Siłownie" link when the user owns a gym — the tile name carries the gym name)
|
||
await user.click(await screen.findByRole('link', { name: /^Siłownie / }));
|
||
// tytuł podstrony jest tylko w topmenu (nagłówek Layout)
|
||
expect(await screen.findByRole('heading', { name: 'Profil — siłownie' })).toBeInTheDocument();
|
||
}
|
||
|
||
beforeEach(async () => {
|
||
await new Promise((r) => setTimeout(r, 25));
|
||
setAccessToken(null);
|
||
localStorage.clear();
|
||
useAuth.setState({ user: null, ready: false });
|
||
});
|
||
|
||
afterEach(() => {
|
||
vi.unstubAllGlobals();
|
||
});
|
||
|
||
describe('Profile — gyms section', () => {
|
||
it('shows the user gym with role and equipment, and a joinable gym', async () => {
|
||
mockApi();
|
||
const user = userEvent.setup();
|
||
const queryClient = new QueryClient({
|
||
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
||
});
|
||
render(
|
||
<QueryClientProvider client={queryClient}>
|
||
<MemoryRouter initialEntries={['/profile']}>
|
||
<App />
|
||
</MemoryRouter>
|
||
</QueryClientProvider>,
|
||
);
|
||
await loginToProfile(user);
|
||
|
||
expect(await screen.findByText('Żelazna Świątynia')).toBeInTheDocument();
|
||
// a user can hold several roles in the same gym
|
||
expect(screen.getByText('Właściciel')).toBeInTheDocument();
|
||
// „Trener" appears both as a gym role badge and as the sidebar role label
|
||
expect(screen.getAllByText('Trener').length).toBeGreaterThan(0);
|
||
// equipment chips show quantity and the type-specific spec
|
||
expect(screen.getByText('sztanga · do 100 kg')).toBeInTheDocument();
|
||
expect(screen.getByText('hantle ×2 · 2.5–25 kg')).toBeInTheDocument();
|
||
expect(screen.getByText('Mega Gym')).toBeInTheDocument();
|
||
expect(screen.getByRole('button', { name: 'Dołącz' })).toBeInTheDocument();
|
||
});
|
||
|
||
it('admin creates a gym from the modal', async () => {
|
||
mockApi({ isAdmin: true });
|
||
const user = userEvent.setup();
|
||
const queryClient = new QueryClient({
|
||
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
||
});
|
||
render(
|
||
<QueryClientProvider client={queryClient}>
|
||
<MemoryRouter initialEntries={['/profile']}>
|
||
<App />
|
||
</MemoryRouter>
|
||
</QueryClientProvider>,
|
||
);
|
||
await loginToProfile(user);
|
||
await screen.findByText('Żelazna Świątynia');
|
||
|
||
// akcja „Stwórz siłownię” jest za ikoną ➕ (grupa dodawania)
|
||
await user.click(screen.getByRole('button', { name: 'Dodawanie' }));
|
||
await user.click(screen.getByRole('button', { name: 'Stwórz siłownię' }));
|
||
const dialog = await screen.findByRole('dialog');
|
||
const nameInput = dialog.querySelector('input') as HTMLInputElement;
|
||
await user.type(nameInput, 'Nowa Siłownia');
|
||
// wirtualna siłownia (domyślny typ) wymaga lokalizacji
|
||
await user.type(screen.getByPlaceholderText('np. Warszawa'), 'Testowo 1');
|
||
await user.click(screen.getByRole('button', { name: 'Utwórz' }));
|
||
expect(await screen.findByText('Siłownia utworzona')).toBeInTheDocument();
|
||
});
|
||
|
||
it('hides the gym creation button for a non-admin user', async () => {
|
||
mockApi();
|
||
const user = userEvent.setup();
|
||
const queryClient = new QueryClient({
|
||
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
||
});
|
||
render(
|
||
<QueryClientProvider client={queryClient}>
|
||
<MemoryRouter initialEntries={['/profile']}>
|
||
<App />
|
||
</MemoryRouter>
|
||
</QueryClientProvider>,
|
||
);
|
||
await loginToProfile(user);
|
||
await screen.findByText('Żelazna Świątynia');
|
||
|
||
// non-admin — brak ikony ➕ w nagłówku (akcja „Stwórz siłownię” nie istnieje)
|
||
expect(screen.queryByRole('button', { name: 'Dodawanie' })).not.toBeInTheDocument();
|
||
});
|
||
|
||
it('joins an existing gym', async () => {
|
||
mockApi();
|
||
const user = userEvent.setup();
|
||
const queryClient = new QueryClient({
|
||
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
||
});
|
||
render(
|
||
<QueryClientProvider client={queryClient}>
|
||
<MemoryRouter initialEntries={['/profile']}>
|
||
<App />
|
||
</MemoryRouter>
|
||
</QueryClientProvider>,
|
||
);
|
||
await loginToProfile(user);
|
||
await screen.findByText('Mega Gym');
|
||
|
||
await user.click(screen.getByRole('button', { name: 'Dołącz' }));
|
||
expect(await screen.findByText('Dołączono do siłowni: Mega Gym')).toBeInTheDocument();
|
||
});
|
||
|
||
it('adds equipment to an owned gym', async () => {
|
||
mockApi();
|
||
const user = userEvent.setup();
|
||
const queryClient = new QueryClient({
|
||
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
||
});
|
||
render(
|
||
<QueryClientProvider client={queryClient}>
|
||
<MemoryRouter initialEntries={['/profile']}>
|
||
<App />
|
||
</MemoryRouter>
|
||
</QueryClientProvider>,
|
||
);
|
||
await loginToProfile(user);
|
||
await screen.findByText('Żelazna Świątynia');
|
||
|
||
const equipSelect = screen.getByLabelText('Dodaj sprzęt do Żelazna Świątynia');
|
||
await user.selectOptions(equipSelect, 'eq-3');
|
||
await waitFor(() => {
|
||
expect(screen.getByText('Kettlebell · 4–32 kg')).toBeInTheDocument();
|
||
});
|
||
expect(screen.getByText('Sprzęt dodany')).toBeInTheDocument();
|
||
});
|
||
|
||
it('adding already-added equipment increases its quantity', async () => {
|
||
mockApi();
|
||
const user = userEvent.setup();
|
||
const queryClient = new QueryClient({
|
||
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
||
});
|
||
render(
|
||
<QueryClientProvider client={queryClient}>
|
||
<MemoryRouter initialEntries={['/profile']}>
|
||
<App />
|
||
</MemoryRouter>
|
||
</QueryClientProvider>,
|
||
);
|
||
await loginToProfile(user);
|
||
await screen.findByText('Żelazna Świątynia');
|
||
expect(screen.getByText('hantle ×2 · 2.5–25 kg')).toBeInTheDocument();
|
||
|
||
// select pokazuje cały katalog — sprzęt już dodany jest oznaczony bieżącą ilością
|
||
const equipSelect = screen.getByLabelText('Dodaj sprzęt do Żelazna Świątynia');
|
||
await user.selectOptions(equipSelect, 'eq-2');
|
||
await waitFor(() => {
|
||
expect(screen.getByText('hantle ×3 · 2.5–25 kg')).toBeInTheDocument();
|
||
});
|
||
expect(screen.getByText('Zwiększono ilość (łącznie 3)')).toBeInTheDocument();
|
||
});
|
||
});
|