227 lines
8.3 KiB
TypeScript
227 lines
8.3 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',
|
|
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 EXERCISES = [{ id: 'ex-1', name: 'Przysiady', primaryMuscle: 'legs' }];
|
|
|
|
function jsonResponse(status: number, body: unknown) {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
interface Capture {
|
|
createPlanBody?: Record<string, unknown>;
|
|
}
|
|
|
|
function mockApi(capture: Capture) {
|
|
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/active-session')) return jsonResponse(200, { session: null });
|
|
if (url.endsWith('/me'))
|
|
return jsonResponse(200, { user: USER, memberships: [] });
|
|
if (url.includes('/exercises')) return jsonResponse(200, { exercises: EXERCISES });
|
|
if (url.includes('/dashboard'))
|
|
return jsonResponse(200, {
|
|
killstreak: 0,
|
|
activePlan: null,
|
|
nextTraining: null,
|
|
progress: null,
|
|
extra: null,
|
|
missing: null,
|
|
});
|
|
if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] });
|
|
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
|
|
if (url.includes('/plans/plan-new'))
|
|
return jsonResponse(200, {
|
|
plan: {
|
|
id: 'plan-new',
|
|
title: 'Plan testowy',
|
|
status: 'ACTIVE',
|
|
weeksCount: 4,
|
|
startDate: '2026-08-24',
|
|
weeks: [],
|
|
},
|
|
});
|
|
if (url.endsWith('/plans')) {
|
|
if (method === 'POST') {
|
|
capture.createPlanBody = JSON.parse(String(init?.body));
|
|
return jsonResponse(201, { plan: { id: 'plan-new' } });
|
|
}
|
|
return jsonResponse(200, { plans: [] });
|
|
}
|
|
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 loginAndOpenNewPlan(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: 'Plany' }));
|
|
expect(await screen.findByRole('heading', { name: 'Plany' })).toBeInTheDocument();
|
|
// „Nowy plan” pojawia się w menu kontekstowym i w pustym stanie listy — klikamy pierwsze (menu)
|
|
await user.click(screen.getAllByRole('button', { name: 'Nowy plan' })[0]);
|
|
expect(await screen.findByRole('heading', { name: 'Nowy plan' })).toBeInTheDocument();
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
await new Promise((r) => setTimeout(r, 25));
|
|
setAccessToken(null);
|
|
localStorage.clear();
|
|
useAuth.setState({ user: null, ready: false });
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
describe('PlanEditor — data startu i menu kontekstowe', () => {
|
|
it('ma wybór tygodnia startu i przekazuje jego poniedziałek do createPlan', async () => {
|
|
const capture: Capture = {};
|
|
mockApi(capture);
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await loginAndOpenNewPlan(user);
|
|
|
|
// wybór tygodnia startu jest widoczny w trybie tworzenia
|
|
expect(screen.getByRole('group', { name: 'Wybór tygodnia startu' })).toBeInTheDocument();
|
|
|
|
// 20. dzień bieżącego miesiąca może być w minionym tygodniu (zablokowany) —
|
|
// wybieramy 20. dzień następnego miesiąca (unikalny w siatce, zawsze przyszły tydzień)
|
|
await user.click(screen.getByRole('button', { name: 'Następny miesiąc' }));
|
|
await user.click(screen.getByRole('button', { name: '20' }));
|
|
|
|
// oczekiwany poniedziałek tygodnia zawierającego 20. dzień następnego miesiąca
|
|
const now = new Date();
|
|
const target = new Date(now.getFullYear(), now.getMonth() + 1, 20);
|
|
const monday = new Date(target);
|
|
monday.setDate(target.getDate() - ((target.getDay() + 6) % 7));
|
|
const expected = `${monday.getFullYear()}-${String(monday.getMonth() + 1).padStart(2, '0')}-${String(
|
|
monday.getDate(),
|
|
).padStart(2, '0')}`;
|
|
|
|
const title = screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy');
|
|
await user.type(title, 'Plan testowy');
|
|
|
|
await user.click(screen.getByRole('button', { name: 'Utwórz plan' }));
|
|
await waitFor(() =>
|
|
expect(capture.createPlanBody).toMatchObject({
|
|
title: 'Plan testowy',
|
|
startDate: expected,
|
|
}),
|
|
);
|
|
});
|
|
|
|
it('blokuje minione tygodnie startu', async () => {
|
|
mockApi({});
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await loginAndOpenNewPlan(user);
|
|
|
|
// siatka = 42 komórki (6 tygodni) z dniami sąsiednich miesięcy — dla KAŻDEJ komórki
|
|
// oczekiwany stan bierze się z poniedziałka jej tygodnia (ten sam numer dnia może
|
|
// występować w minionym i przyszłym tygodniu, więc sprawdzamy komórkę po komórce)
|
|
const now = new Date();
|
|
const y = now.getFullYear();
|
|
const m = now.getMonth() + 1;
|
|
const firstDay = new Date(y, m - 1, 1);
|
|
const startOffset = (firstDay.getDay() + 6) % 7;
|
|
const gridStart = new Date(y, m - 1, 1 - startOffset);
|
|
const cells = Array.from({ length: 42 }, (_, i) => {
|
|
const d = new Date(gridStart);
|
|
d.setDate(gridStart.getDate() + i);
|
|
return d;
|
|
});
|
|
const mondayOf = (d: Date) => {
|
|
const x = new Date(d.getFullYear(), d.getMonth(), d.getDate());
|
|
x.setDate(x.getDate() - ((x.getDay() + 6) % 7));
|
|
return x;
|
|
};
|
|
const curMonday = mondayOf(now);
|
|
|
|
const group = screen.getByRole('group', { name: 'Wybór tygodnia startu' });
|
|
const buttons = within(group).getAllByRole('button');
|
|
expect(buttons).toHaveLength(42);
|
|
for (let i = 0; i < 42; i++) {
|
|
expect((buttons[i] as HTMLButtonElement).disabled).toBe(mondayOf(cells[i]) < curMonday);
|
|
}
|
|
});
|
|
|
|
it('nie wysyła startDate, gdy nie zaznaczono tygodnia startu', async () => {
|
|
const capture: Capture = {};
|
|
mockApi(capture);
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await loginAndOpenNewPlan(user);
|
|
|
|
const title = screen.getByPlaceholderText('np. Plan masowy 8-tygodniowy');
|
|
await user.type(title, 'Plan szkic');
|
|
await user.click(screen.getByRole('button', { name: 'Utwórz plan' }));
|
|
await waitFor(() => expect(capture.createPlanBody).toBeDefined());
|
|
expect(capture.createPlanBody).not.toHaveProperty('startDate');
|
|
});
|
|
|
|
it('pokazuje „Wstecz” w treści formularza na /plans/new', async () => {
|
|
mockApi({});
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await loginAndOpenNewPlan(user);
|
|
// „Wstecz” jest też w topmenu (wariant mobilny) — sprawdzamy ten w treści strony
|
|
const content = document.querySelector('.max-w-5xl');
|
|
expect(content).not.toBeNull();
|
|
expect(within(content!).getByRole('button', { name: 'Wstecz' })).toBeInTheDocument();
|
|
});
|
|
});
|