350 lines
14 KiB
TypeScript
350 lines
14 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 { monthStr } from '../src/lib/format';
|
|
import { formatMonth } from '../src/lib/format';
|
|
import type { User } from '../src/api/types';
|
|
|
|
const USER: User = {
|
|
id: 'u1',
|
|
email: 'jan@test.local',
|
|
firstName: 'Jan',
|
|
lastName: 'Kowalski',
|
|
birthDate: '1996-05-05T00:00:00.000Z',
|
|
heightCm: 180,
|
|
phone: '+48 600 000 000',
|
|
isAdmin: false,
|
|
availability: null,
|
|
priorities: null,
|
|
exclusions: null,
|
|
developMuscles: [],
|
|
canDoMuscles: [],
|
|
difficultMuscles: [],
|
|
avoidMuscles: [],
|
|
createdAt: '2026-08-22T10:00:00.000Z',
|
|
};
|
|
|
|
function jsonResponse(status: number, body: unknown) {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
function mockApi() {
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn(async (input: RequestInfo | URL) => {
|
|
const url = String(input);
|
|
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.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
|
|
if (url.includes('/dashboard'))
|
|
return jsonResponse(200, {
|
|
killstreak: 0,
|
|
activePlan: null,
|
|
nextTraining: null,
|
|
progress: null,
|
|
extra: null,
|
|
missing: null,
|
|
});
|
|
if (url.includes('/calendar')) return jsonResponse(200, { month: '2026-08', days: [] });
|
|
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: [] });
|
|
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
|
|
}),
|
|
);
|
|
}
|
|
|
|
function renderApp() {
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
|
});
|
|
render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<MemoryRouter initialEntries={['/']}>
|
|
<App />
|
|
</MemoryRouter>
|
|
</QueryClientProvider>,
|
|
);
|
|
}
|
|
|
|
async function openCalendar(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: 'Mój kalendarz' }));
|
|
expect(await screen.findByRole('heading', { name: 'Kalendarz' })).toBeInTheDocument();
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
await new Promise((r) => setTimeout(r, 25));
|
|
setAccessToken(null);
|
|
localStorage.clear();
|
|
useAuth.setState({ user: null, ready: false });
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
const ACTIVE_SESSION = {
|
|
id: 'sess-1',
|
|
dayId: 'day-1',
|
|
dayDate: '2026-08-24',
|
|
dayOfWeek: 1,
|
|
planTitle: 'Plan testowy',
|
|
startedAt: '2026-08-24T07:00:00.000Z',
|
|
};
|
|
|
|
/** Kalendarz z jednym dniem zaplanowanym na dziś + opcjonalna aktywna sesja. */
|
|
function mockApiWithDay(active: unknown) {
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn(async (input: RequestInfo | URL) => {
|
|
const url = String(input);
|
|
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: active });
|
|
if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
|
|
if (url.includes('/dashboard'))
|
|
return jsonResponse(200, {
|
|
killstreak: 0,
|
|
activePlan: null,
|
|
nextTraining: null,
|
|
progress: null,
|
|
extra: null,
|
|
missing: null,
|
|
});
|
|
if (url.includes('/calendar'))
|
|
return jsonResponse(200, {
|
|
month: monthStr(new Date()),
|
|
days: [
|
|
{
|
|
id: 'day-1',
|
|
date: new Date().toISOString(),
|
|
status: 'PLANNED',
|
|
dayOfWeek: 1,
|
|
planId: 'plan-1',
|
|
planTitle: 'Plan testowy',
|
|
planStartDate: '2026-08-10T00:00:00.000Z',
|
|
moves: 0,
|
|
exercises: [{ name: 'Przysiady', muscle: 'legs' }],
|
|
},
|
|
],
|
|
});
|
|
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: [] });
|
|
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
|
|
}),
|
|
);
|
|
}
|
|
|
|
describe('Kalendarz — CTA karty dnia wg stanu sesji', () => {
|
|
it('dzień zaplanowany bez aktywnej sesji: „Rozpocznij trening”', async () => {
|
|
mockApiWithDay(null);
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await openCalendar(user);
|
|
|
|
// wybór dnia z listy mobilnej (siatka ukryta w jsdom)
|
|
await user.click(screen.getByRole('button', { name: /Zaplanowany/ }));
|
|
expect(await screen.findByRole('button', { name: 'Rozpocznij trening' })).toBeInTheDocument();
|
|
expect(screen.queryByRole('button', { name: 'Wróć do treningu' })).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('dzień z aktywną sesją: „Wróć do treningu” zamiast „Rozpocznij trening”', async () => {
|
|
mockApiWithDay(ACTIVE_SESSION);
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await openCalendar(user);
|
|
|
|
await user.click(screen.getByRole('button', { name: /Zaplanowany/ }));
|
|
expect(await screen.findByRole('button', { name: 'Wróć do treningu' })).toBeInTheDocument();
|
|
expect(screen.queryByRole('button', { name: 'Rozpocznij trening' })).not.toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
describe('Kalendarz — przesunięcie dnia treningowego', () => {
|
|
interface MoveCapture {
|
|
moveBodies: Record<string, unknown>[];
|
|
}
|
|
|
|
/** Kalendarz z jednym PLANNED dniem aktywnego planu; PATCH move wg `mode`. */
|
|
function mockMoveApi(capture: MoveCapture, mode: 'ok' | 'conflict') {
|
|
let moveCalls = 0;
|
|
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.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
|
|
if (url.includes('/dashboard'))
|
|
return jsonResponse(200, {
|
|
killstreak: 0,
|
|
activePlan: null,
|
|
nextTraining: null,
|
|
progress: null,
|
|
extra: null,
|
|
missing: null,
|
|
});
|
|
if (
|
|
url.includes('/plans/plan-1/days/day-1/move') &&
|
|
method === 'PATCH'
|
|
) {
|
|
moveCalls += 1;
|
|
capture.moveBodies.push(JSON.parse(String(init?.body)));
|
|
if (mode === 'conflict' && moveCalls === 1)
|
|
return jsonResponse(409, {
|
|
error: {
|
|
code: 'PLAN_DAY_TAKEN',
|
|
message: 'Another training is already planned on that date',
|
|
details: { conflictDayId: 'day-2', conflictDate: '2026-08-31T00:00:00.000Z' },
|
|
},
|
|
});
|
|
return jsonResponse(200, {
|
|
day: { id: 'day-1', date: '2026-08-31T00:00:00.000Z', status: 'PLANNED', dayOfWeek: 1 },
|
|
swappedWith: null,
|
|
});
|
|
}
|
|
if (url.includes('/calendar'))
|
|
return jsonResponse(200, {
|
|
month: monthStr(new Date()),
|
|
days: [
|
|
{
|
|
id: 'day-1',
|
|
date: new Date().toISOString(),
|
|
status: 'PLANNED',
|
|
dayOfWeek: 1,
|
|
planId: 'plan-1',
|
|
planTitle: 'Plan testowy',
|
|
planStartDate: '2026-08-10T00:00:00.000Z',
|
|
moves: 0,
|
|
exercises: [{ name: 'Przysiady', muscle: 'legs' }],
|
|
},
|
|
],
|
|
});
|
|
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: [] });
|
|
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
|
|
}),
|
|
);
|
|
}
|
|
|
|
it('wybrany dzień planu aktywnego: akcja „Przesuń dzień” w topmenu i PATCH z datą', async () => {
|
|
const capture: MoveCapture = { moveBodies: [] };
|
|
mockMoveApi(capture, 'ok');
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await openCalendar(user);
|
|
|
|
const header = document.querySelector('header')!;
|
|
await user.click(screen.getByRole('button', { name: /Zaplanowany/ }));
|
|
await user.click(within(header).getByRole('button', { name: 'Przesuń dzień' }));
|
|
|
|
const dialog = await screen.findByRole('dialog', { name: 'Przesunięcie dnia treningowego' });
|
|
expect(dialog.querySelector('input[type="date"]')).toBeInTheDocument();
|
|
await user.click(within(dialog).getByRole('button', { name: 'Przesuń' }));
|
|
await waitFor(() => expect(capture.moveBodies).toHaveLength(1));
|
|
expect(capture.moveBodies[0]).toMatchObject({ date: expect.stringMatching(/^\d{4}-\d{2}-\d{2}$/) });
|
|
});
|
|
|
|
it('konflikt terminu (PLAN_DAY_TAKEN): dialog proponuje zamianę i wysyła swapWithDayId', async () => {
|
|
const capture: MoveCapture = { moveBodies: [] };
|
|
mockMoveApi(capture, 'conflict');
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await openCalendar(user);
|
|
|
|
const header = document.querySelector('header')!;
|
|
await user.click(screen.getByRole('button', { name: /Zaplanowany/ }));
|
|
await user.click(within(header).getByRole('button', { name: 'Przesuń dzień' }));
|
|
const dialog = await screen.findByRole('dialog', { name: 'Przesunięcie dnia treningowego' });
|
|
await user.click(within(dialog).getByRole('button', { name: 'Przesuń' }));
|
|
|
|
expect(await within(dialog).findByText(/już zaplanowany inny trening/)).toBeInTheDocument();
|
|
await user.click(within(dialog).getByRole('button', { name: 'Zamień dni' }));
|
|
await waitFor(() => expect(capture.moveBodies).toHaveLength(2));
|
|
expect(capture.moveBodies[1]).toMatchObject({ swapWithDayId: 'day-2' });
|
|
});
|
|
});
|
|
|
|
describe('Kalendarz — nawigacja miesiąca w top menu', () => {
|
|
it('przyciski „Poprzedni/Następny miesiąc” zmieniają miesiąc (z rolowaniem roku)', async () => {
|
|
mockApi();
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await openCalendar(user);
|
|
|
|
const now = new Date();
|
|
const cur = monthStr(now);
|
|
const [y, m] = cur.split('-').map(Number);
|
|
const next = monthStr(new Date(y, m, 1));
|
|
|
|
// tytuł miesiąca w top menu
|
|
expect(screen.getByRole('button', { name: formatMonth(cur) })).toBeInTheDocument();
|
|
|
|
await user.click(screen.getByRole('button', { name: 'Następny miesiąc' }));
|
|
expect(await screen.findByRole('button', { name: formatMonth(next) })).toBeInTheDocument();
|
|
|
|
await user.click(screen.getByRole('button', { name: 'Poprzedni miesiąc' }));
|
|
expect(await screen.findByRole('button', { name: formatMonth(cur) })).toBeInTheDocument();
|
|
|
|
// m kroków wstecz od miesiąca m trafia na grudzień poprzedniego roku (rolowanie roku)
|
|
for (let i = 0; i < m; i++) {
|
|
await user.click(screen.getByRole('button', { name: 'Poprzedni miesiąc' }));
|
|
}
|
|
const prevYearDec = monthStr(new Date(y - 1, 11, 1));
|
|
expect(
|
|
await screen.findByRole('button', { name: formatMonth(prevYearDec) }),
|
|
).toBeInTheDocument();
|
|
});
|
|
|
|
it('„idź do miesiąca”: siatka 12 miesięcy z wyborem roku', async () => {
|
|
mockApi();
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await openCalendar(user);
|
|
|
|
const now = new Date();
|
|
const cur = monthStr(now);
|
|
const [y] = cur.split('-').map(Number);
|
|
|
|
// otwarcie panelu przyciskiem z tytułem bieżącego miesiąca
|
|
await user.click(screen.getByRole('button', { name: formatMonth(cur) }));
|
|
expect(screen.getByRole('button', { name: 'Poprzedni rok' })).toBeInTheDocument();
|
|
expect(screen.getByRole('button', { name: 'Następny rok' })).toBeInTheDocument();
|
|
|
|
// krok roku do przodu i wybór stycznia następnego roku
|
|
await user.click(screen.getByRole('button', { name: 'Następny rok' }));
|
|
expect(screen.getByText(String(y + 1))).toBeInTheDocument();
|
|
await user.click(screen.getByRole('button', { name: 'Sty', exact: true }));
|
|
|
|
expect(
|
|
await screen.findByRole('button', { name: formatMonth(`${y + 1}-01`) }),
|
|
).toBeInTheDocument();
|
|
});
|
|
});
|