216 lines
8.1 KiB
TypeScript
216 lines
8.1 KiB
TypeScript
import { render, screen } 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: '+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();
|
|
/** Key dnia względnego (jak StreakDots: ISO.slice(0,10) vs klucz lokalny). */
|
|
const dayKey = (daysAgo: number) => {
|
|
const d = new Date();
|
|
d.setDate(d.getDate() - daysAgo);
|
|
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
|
|
d.getDate(),
|
|
).padStart(2, '0')}`;
|
|
};
|
|
|
|
/** Dzień skutecznej sesji n dni temu w formacie kontraktu (ISO — frontend tnie do daty). */
|
|
const effDay = (daysAgo: number) => `${dayKey(daysAgo)}T07:00:00.000Z`;
|
|
|
|
/** Ciało GET /dashboard z pełnymi polami motywacyjnymi; `overrides` nadpisuje pola. */
|
|
function dashBody(overrides: Record<string, unknown> = {}) {
|
|
return {
|
|
killstreak: 3,
|
|
killstreakBest: 5,
|
|
killstreakDays: [effDay(2), effDay(1), effDay(0)],
|
|
history: { completedPlans: 1, sessions: 12, sets: 96 },
|
|
week: { planned: 3, completed: 1 },
|
|
lastSessionAt: ago(1),
|
|
firstSessionAt: ago(29),
|
|
weeklySets: [0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 9].map((sets, i) => ({
|
|
weekStart: ago(7 * (11 - i)),
|
|
sets,
|
|
})),
|
|
nextTraining: null,
|
|
progress: { completed: 4, total: 5, percent: 80 },
|
|
extra: { sets: 0 },
|
|
missing: { sets: 0 },
|
|
activePlan: { id: 'plan-1', title: 'Plan testowy', startDate: ago(10) },
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
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) => {
|
|
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/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);
|
|
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 } },
|
|
});
|
|
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' }));
|
|
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
|
|
}
|
|
|
|
beforeEach(() => {
|
|
setAccessToken(null);
|
|
localStorage.clear();
|
|
useAuth.setState({ user: null, ready: false });
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
describe('Dashboard — statystyki motywacyjne', () => {
|
|
it('sekcja „Aktywny plan": tempo tygodnia i polska odmiana („1 dzień do końca”)', async () => {
|
|
mockApi(dashBody());
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await login(user);
|
|
|
|
expect(await screen.findByText('Tempo w tym tygodniu', { exact: true })).toBeInTheDocument();
|
|
expect(screen.getByText('1/3', { exact: true })).toBeInTheDocument();
|
|
expect(screen.getByText('ukończone / zaplanowane w tym tygodniu')).toBeInTheDocument();
|
|
// 4 z 5 dni => został 1 DZIEŃ (nie „1 dni”).
|
|
expect(screen.getByText(/1 dzień do końca/)).toBeInTheDocument();
|
|
// Stara karta „Postęp” (netto serii) zniknęła.
|
|
expect(screen.queryByText('Postęp', { exact: true })).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('planned = 0: tempo pokazuje „—” z czytelnym dopiskiem', async () => {
|
|
mockApi(dashBody({ week: { planned: 0, completed: 0 } }));
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await login(user);
|
|
|
|
expect(await screen.findByText('brak treningów w tym tygodniu')).toBeInTheDocument();
|
|
});
|
|
|
|
it('sekcja „Historia": rekord passy, bez kart „Treningi" i „Trenujesz od"', async () => {
|
|
mockApi(dashBody());
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await login(user);
|
|
|
|
expect(await screen.findByText('najwyższy wynik: 5 dni')).toBeInTheDocument();
|
|
expect(screen.getByText('Ukończone plany', { exact: true })).toBeInTheDocument();
|
|
// Dorobek treningów w kafelku „Ukończone plany" (12 sesji z mocka).
|
|
expect(screen.getByText('12', { exact: true })).toBeInTheDocument();
|
|
expect(screen.getByText('ukończone treningi', { exact: true })).toBeInTheDocument();
|
|
expect(screen.queryByText('ostatni: wczoraj')).not.toBeInTheDocument();
|
|
expect(screen.queryByText('Treningi', { exact: true })).not.toBeInTheDocument();
|
|
expect(screen.queryByText('Trenujesz od', { exact: true })).not.toBeInTheDocument();
|
|
});
|
|
|
|
it('kafelek „Serie" renderuje prawdziwy wykres dwunastu tygodni', async () => {
|
|
mockApi(dashBody());
|
|
const user = userEvent.setup();
|
|
const { container } = renderApp();
|
|
await login(user);
|
|
|
|
expect(await screen.findByText('96', { exact: true })).toBeInTheDocument();
|
|
// Wykres WeekBars: dokładnie 12 słupków.
|
|
expect(
|
|
container.querySelectorAll('[data-testid="week-bars"] rect'),
|
|
).toHaveLength(12);
|
|
});
|
|
|
|
it('kropki killstreaka: 30 dni, wypełnione = skuteczne sesje', async () => {
|
|
mockApi(dashBody());
|
|
const user = userEvent.setup();
|
|
const { container } = renderApp();
|
|
await login(user);
|
|
|
|
await screen.findByText('najwyższy wynik: 5 dni');
|
|
const dots = container.querySelectorAll('[data-testid="streak-dots"] span');
|
|
expect(dots).toHaveLength(30);
|
|
const on = [...dots].filter((el) => (el.getAttribute('class') ?? '').includes('bg-accent'));
|
|
expect(on).toHaveLength(3);
|
|
// Ostatnie trzy kropki (wczoraj, przedwczoraj, dziś) — zgodne z mockiem.
|
|
expect([...dots].slice(-3).every((el) => (el.getAttribute('class') ?? '').includes('bg-accent'))).toBe(true);
|
|
});
|
|
|
|
it('bez dorobku (same zera, brak sesji): sekcja „Historia” ukryta', async () => {
|
|
mockApi(
|
|
dashBody({
|
|
killstreak: 0,
|
|
killstreakBest: 0,
|
|
killstreakDays: [],
|
|
history: { completedPlans: 0, sessions: 0, sets: 0 },
|
|
lastSessionAt: null,
|
|
firstSessionAt: null,
|
|
weeklySets: [],
|
|
}),
|
|
);
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await login(user);
|
|
|
|
expect(await screen.findByText('Tempo w tym tygodniu', { exact: true })).toBeInTheDocument();
|
|
expect(screen.queryByText('Historia', { exact: true })).not.toBeInTheDocument();
|
|
});
|
|
});
|