248 lines
9.0 KiB
TypeScript
248 lines
9.0 KiB
TypeScript
import { fireEvent, 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',
|
|
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',
|
|
};
|
|
|
|
const DAY = 86_400_000;
|
|
const ago = (days: number) => new Date(Date.now() - days * DAY).toISOString();
|
|
const isoIn = (days: number) => {
|
|
const d = new Date();
|
|
d.setDate(d.getDate() + days);
|
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
|
|
d.getDate(),
|
|
).padStart(2, '0')}`;
|
|
};
|
|
|
|
function pendingSkip(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
dayId: 'day-skip',
|
|
date: ago(2),
|
|
skippedAt: ago(2),
|
|
exerciseCount: 1,
|
|
unresolvedCount: 2,
|
|
plan: { id: 'plan-1', title: 'Plan testowy', startDate: ago(10) },
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function dashBody(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
killstreak: 0,
|
|
killstreakBest: 0,
|
|
killstreakDays: [],
|
|
history: { completedPlans: 0, sessions: 0, sets: 0 },
|
|
week: null,
|
|
lastSessionAt: null,
|
|
firstSessionAt: null,
|
|
weeklySets: [],
|
|
nextTraining: null,
|
|
progress: { completed: 4, total: 5, percent: 80 },
|
|
pendingSkip: null,
|
|
extra: { sets: 0 },
|
|
missing: { sets: 0 },
|
|
activePlan: { id: 'plan-1', title: 'Plan testowy', startDate: ago(10) },
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
const calls: { method: string; url: string; body: unknown }[] = [];
|
|
|
|
function jsonResponse(status: number, body: unknown) {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
function mockApi(dash: unknown) {
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = String(input);
|
|
const method = (init?.method ?? 'GET').toUpperCase();
|
|
calls.push({ method, url, body: init?.body ? JSON.parse(String(init.body)) : null });
|
|
if (method === 'POST' && url.includes('/skip/accept'))
|
|
return jsonResponse(200, { day: { id: 'day-skip', status: 'SKIPPED' } });
|
|
if (method === 'PATCH' && url.includes('/move'))
|
|
return jsonResponse(200, {
|
|
day: { id: 'day-skip', date: new Date().toISOString(), status: 'PLANNED', dayOfWeek: 1 },
|
|
swappedWith: null,
|
|
});
|
|
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/feed')) return jsonResponse(200, { items: [], nextCursor: null });
|
|
if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
|
|
if (url.includes('/dashboard')) return jsonResponse(200, dash);
|
|
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
|
|
}),
|
|
);
|
|
}
|
|
|
|
function renderApp() {
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
|
});
|
|
return render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<MemoryRouter initialEntries={['/']}>
|
|
<App />
|
|
</MemoryRouter>
|
|
</QueryClientProvider>,
|
|
);
|
|
}
|
|
|
|
async function login(user: ReturnType<typeof userEvent.setup>) {
|
|
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' }));
|
|
// dialog decyzji startuje od razu po wczytaniu -> reszta aplikacji ma aria-hidden,
|
|
// więc role-queries nie widzą h1 Topbaru; sprawdzamy DOM bezpośrednio
|
|
await waitFor(() =>
|
|
expect(
|
|
Array.from(document.querySelectorAll('h1')).some((h) => h.textContent === 'Dashboard'),
|
|
).toBe(true),
|
|
);
|
|
}
|
|
|
|
async function openSkipDialog(user: ReturnType<typeof userEvent.setup>) {
|
|
mockApi(dashBody({ pendingSkip: pendingSkip() }));
|
|
renderApp();
|
|
await login(user);
|
|
return screen.findByRole('heading', { name: 'Pominięty dzień treningowy' });
|
|
}
|
|
|
|
beforeEach(() => {
|
|
calls.length = 0;
|
|
setAccessToken(null);
|
|
localStorage.clear();
|
|
sessionStorage.clear();
|
|
useAuth.setState({ user: null, ready: false });
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
describe('Dashboard — dialog decyzji o pominiętym dniu', () => {
|
|
it('pendingSkip otwiera dialog z treścią i licznikiem pozostałych pominięć', async () => {
|
|
const user = userEvent.setup();
|
|
const title = await openSkipDialog(user);
|
|
expect(title).toBeInTheDocument();
|
|
// plan + treść o serii; licznik: unresolvedCount 2 => „jeszcze 1” (pluralika PL)
|
|
expect(screen.getByText(/został pominięty/)).toBeInTheDocument();
|
|
expect(screen.getByText(/przerywają serię/)).toBeInTheDocument();
|
|
expect(screen.getByText('Czeka jeszcze 1 pominięty dzień.')).toBeInTheDocument();
|
|
// oba rozwiązania decyzji, bez akcji w topbarze
|
|
expect(screen.getByRole('button', { name: 'Zostaw pominięty' })).toBeInTheDocument();
|
|
expect(screen.getByRole('button', { name: 'Przesuń dzień' })).toBeInTheDocument();
|
|
});
|
|
|
|
it('„Zostaw pominięty” → POST skip/accept, toast i zniknięcie dialogu', async () => {
|
|
const user = userEvent.setup();
|
|
await openSkipDialog(user);
|
|
await user.click(screen.getByRole('button', { name: 'Zostaw pominięty' }));
|
|
expect(await screen.findByText('Dzień pozostał pominięty.')).toBeInTheDocument();
|
|
await waitFor(() =>
|
|
expect(calls).toContainEqual(
|
|
expect.objectContaining({
|
|
method: 'POST',
|
|
url: expect.stringContaining('/plans/plan-1/days/day-skip/skip/accept'),
|
|
}),
|
|
),
|
|
);
|
|
await waitFor(() =>
|
|
expect(
|
|
screen.queryByRole('heading', { name: 'Pominięty dzień treningowy' }),
|
|
).not.toBeInTheDocument(),
|
|
);
|
|
});
|
|
|
|
it('X/Esc to nie decyzja: brak POST, a ponowne wejście na Dashboard nie pokazuje dialogu', async () => {
|
|
const user = userEvent.setup();
|
|
await openSkipDialog(user);
|
|
await user.keyboard('{Escape}');
|
|
await waitFor(() =>
|
|
expect(
|
|
screen.queryByRole('heading', { name: 'Pominięty dzień treningowy' }),
|
|
).not.toBeInTheDocument(),
|
|
);
|
|
expect(calls.some((c) => c.url.includes('/skip/accept'))).toBe(false);
|
|
expect(sessionStorage.getItem('fitos-skip-dismissed')).toContain('day-skip');
|
|
|
|
// powrót na Dashboard w tej samej sesji karty: ten sam dzień nie startuje dialogu ponownie
|
|
renderApp();
|
|
await waitFor(() =>
|
|
expect(
|
|
Array.from(document.querySelectorAll('h1')).some((h) => h.textContent === 'Dashboard'),
|
|
).toBe(true),
|
|
);
|
|
expect(
|
|
screen.queryByRole('heading', { name: 'Pominięty dzień treningowy' }),
|
|
).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('„Przesuń dzień” otwiera MoveDayDialog i PATCH move z nową datą', async () => {
|
|
const user = userEvent.setup();
|
|
await openSkipDialog(user);
|
|
await user.click(screen.getByRole('button', { name: 'Przesuń dzień' }));
|
|
|
|
const dialog = await screen.findByRole('dialog', { name: 'Przesunięcie dnia treningowego' });
|
|
const target = isoIn(5);
|
|
const dateInput = dialog.querySelector('input[type="date"]') as HTMLInputElement;
|
|
fireEvent.change(dateInput, { target: { value: target } });
|
|
await user.click(within(dialog).getByRole('button', { name: 'Przesuń' }));
|
|
|
|
await waitFor(() =>
|
|
expect(calls).toContainEqual(
|
|
expect.objectContaining({
|
|
method: 'PATCH',
|
|
url: expect.stringContaining('/plans/plan-1/days/day-skip/move'),
|
|
body: expect.objectContaining({ date: target }),
|
|
}),
|
|
),
|
|
);
|
|
expect(await screen.findByText(/Trening przesunięty na/)).toBeInTheDocument();
|
|
});
|
|
|
|
it('brak pendingSkip w odpowiedzi (starszy kontrakt/mock): dialog się nie pokazuje', async () => {
|
|
const user = userEvent.setup();
|
|
mockApi(dashBody());
|
|
renderApp();
|
|
await login(user);
|
|
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
|
|
expect(
|
|
screen.queryByRole('heading', { name: 'Pominięty dzień treningowy' }),
|
|
).not.toBeInTheDocument();
|
|
});
|
|
});
|