Files
FitOS/app/test/PlanEditor.test.tsx
2026-09-04 19:06:19 +02:00

207 lines
7.6 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 } 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);
// ostatni dzień poprzedniego tygodnia — jego przycisk jest zablokowany
// (ten sam numer może powtórzyć się w komórках sąsiednich miesięcy — to też minione tygodnie)
const prevWeekEnd = new Date();
prevWeekEnd.setDate(prevWeekEnd.getDate() - ((prevWeekEnd.getDay() + 6) % 7) - 1);
if (prevWeekEnd.getMonth() !== new Date().getMonth()) {
await user.click(screen.getByRole('button', { name: 'Poprzedni miesiąc' }));
}
const buttons = screen.getAllByRole('button', { name: String(prevWeekEnd.getDate()), exact: true });
expect(buttons.length).toBeGreaterThan(0);
for (const b of buttons) expect((b as HTMLButtonElement).disabled).toBe(true);
});
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);
expect(screen.getByRole('button', { name: 'Wstecz' })).toBeInTheDocument();
});
});