Files
FitOS/app/test/PlanDetail.test.tsx

321 lines
11 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, 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 OWNER: 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 RECIPIENT: User = {
...OWNER,
id: 'u2',
email: 'anna@test.local',
firstName: 'Anna',
lastName: 'Nowak',
};
const TRAINEE = {
user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null },
gyms: [{ id: 'gym-1', name: 'Żelazna Świątynia' }],
activePlan: null,
killstreak: 0,
lastSessionAt: null,
flags: [],
};
/** Detal planu (właściciel = u1); warianty: canManage / shares / sharedBy. */
function planDetail(overrides: Record<string, unknown> = {}) {
return {
id: 'plan-1',
userId: 'u1',
title: 'Plan masowy',
status: 'DRAFT',
weeksCount: 1,
startDate: null,
gym: null,
creator: null,
canManage: true,
shares: [],
weeks: [
{
id: 'tw-1',
index: 0,
customName: null,
days: [
{
id: 'td-1',
dayOfWeek: 1,
date: null,
status: 'PLANNED',
moveLog: [],
sessions: [],
exercises: [
{
id: 'tpe-1',
exerciseId: 'ex-1',
order: 0,
exercise: { id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' },
sets: [
{
id: 'tps-1',
index: 0,
reps: 10,
loadKg: 60,
restSec: 90,
rir: 2,
cardioBpm: null,
timeSec: null,
speed: null,
},
],
},
],
},
],
},
],
...overrides,
};
}
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
interface MockOpts {
user: User;
memberships?: { gymId: string; roles: string[] }[];
plans?: Record<string, unknown>[];
sharedWithMe?: Record<string, unknown>[];
plan?: Record<string, unknown>;
trainees?: unknown[];
trainers?: unknown[];
}
interface Capture {
shareBody?: Record<string, unknown>;
}
function mockApi(capture: Capture, opts: MockOpts) {
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: opts.user, accessToken: 'tok-1' });
if (url.includes('/auth/refresh'))
return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } });
if (url.includes('/me/active-session')) return jsonResponse(200, { session: null });
if (url.endsWith('/me'))
return jsonResponse(200, { user: opts.user, memberships: opts.memberships ?? [] });
if (url.includes('/me/trainers'))
return jsonResponse(200, { trainers: opts.trainers ?? [] });
if (url.includes('/trainer/trainees'))
return jsonResponse(200, { trainees: opts.trainees ?? [] });
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('/gyms')) return jsonResponse(200, { gyms: [] });
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
if (url.includes('/plans/shared-with-me'))
return jsonResponse(200, { plans: opts.sharedWithMe ?? [] });
if (url.includes('/plans/plan-1/share')) {
if (method === 'POST') {
capture.shareBody = JSON.parse(String(init?.body));
return jsonResponse(201, { ok: true });
}
if (method === 'DELETE') return jsonResponse(200, { ok: true });
}
if (url.endsWith('/plans')) return jsonResponse(200, { plans: opts.plans ?? [] });
if (url.includes('/plans/plan-1'))
return jsonResponse(200, { plan: opts.plan ?? planDetail() });
return jsonResponse(200, {});
}),
);
}
function renderApp() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
}
async function loginAndOpenPlans(user: userEvent.User, email: string) {
expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument();
const emailInput = document.querySelector('input[type="email"]') as HTMLInputElement;
const password = document.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(emailInput, email);
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: 'Plany' }));
expect(await screen.findByRole('heading', { name: 'Plany' })).toBeInTheDocument();
}
beforeEach(async () => {
await new Promise((r) => setTimeout(r, 25));
setAccessToken(null);
localStorage.clear();
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('PlanDetail — udostępnianie planów (WP4)', () => {
it('właściciel: akcje w topmenu (Aktywuj/Edytuj/Usuń/Udostępnij) i wybór tygodnia startu', async () => {
mockApi(
{},
{
user: OWNER,
memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }],
plans: [planDetail()],
},
);
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
const header = document.querySelector('header')!;
expect(within(header).getByRole('button', { name: 'Aktywuj' })).toBeInTheDocument();
expect(within(header).getByRole('button', { name: 'Edytuj' })).toBeInTheDocument();
expect(within(header).getByRole('button', { name: 'Usuń' })).toBeInTheDocument();
expect(within(header).getByRole('button', { name: 'Udostępnij' })).toBeInTheDocument();
// DRAFT + canManage — wybór tygodnia startu w karcie
expect(screen.getByText('Tydzień startu')).toBeInTheDocument();
});
it('odbiorca share’a: sekcja „Udostępnione mi”, plan read-only (bez akcji i bez tygodnia startu)', async () => {
const shared = planDetail({
canManage: false,
shares: undefined,
sharedBy: { id: 'u1', firstName: 'Jan', lastName: 'Kowalski' },
});
mockApi(
{},
{
user: RECIPIENT,
plans: [],
sharedWithMe: [shared],
plan: shared,
},
);
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, RECIPIENT.email);
// sekcja „Udostępnione mi” z etykietą twórcy
expect(screen.getByRole('heading', { name: 'Udostępnione mi' })).toBeInTheDocument();
expect(screen.getByText('udostępnił: Jan Kowalski')).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
// read-only: brak akcji statusowych, „Udostępnij” i wyboru tygodnia startu
expect(screen.queryByRole('button', { name: 'Aktywuj' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Edytuj' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Usuń' })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Udostępnij' })).not.toBeInTheDocument();
expect(screen.queryByText('Tydzień startu')).not.toBeInTheDocument();
});
it('dialog „Udostępnij plan”: podopieczni z checkboxem, share = POST /plans/:id/share', async () => {
const capture: Capture = {};
mockApi(
capture,
{
user: OWNER,
memberships: [{ gymId: 'gym-1', roles: ['TRAINER'] }],
plans: [planDetail()],
trainees: [TRAINEE],
},
);
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Udostępnij' }));
const dialog = await screen.findByRole('dialog', { name: 'Udostępnij plan' });
expect(within(dialog).getByText('Moje podopieczne')).toBeInTheDocument();
expect(within(dialog).getByText('Anna Nowak')).toBeInTheDocument();
const checkbox = within(dialog).getByRole('checkbox') as HTMLInputElement;
await user.click(checkbox);
await waitFor(() =>
expect(capture.shareBody).toMatchObject({ userId: 'trainee-1' }),
);
});
it('właściciel z udostępnionym planem: etykieta „udostępnione: …” w meta', async () => {
mockApi(
{},
{
user: OWNER,
plans: [planDetail()],
plan: planDetail({
shares: [
{
userId: 'trainee-1',
user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak' },
},
],
}),
},
);
const user = userEvent.setup();
renderApp();
await loginAndOpenPlans(user, OWNER.email);
await user.click(screen.getByRole('link', { name: /Otwórz/ }));
expect(await screen.findByRole('heading', { name: 'Plan masowy' })).toBeInTheDocument();
expect(screen.getByText('udostępnione: Anna Nowak')).toBeInTheDocument();
});
});