175 lines
6.2 KiB
TypeScript
175 lines
6.2 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 ACTIVE_SESSION = {
|
|
id: 'sess-1',
|
|
dayId: 'day-1',
|
|
dayDate: '2026-08-24',
|
|
dayOfWeek: 1,
|
|
planTitle: 'Plan testowy',
|
|
startedAt: '2026-08-24T07:00:00.000Z',
|
|
};
|
|
|
|
function jsonResponse(status: number, body: unknown) {
|
|
return new Response(JSON.stringify(body), {
|
|
status,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
/** Mockuje API; `active` = ciało GET /me/active-session (session: null lub obiekt). */
|
|
function mockApi(active: unknown, calls: { activeSession: number }) {
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
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')) {
|
|
calls.activeSession++;
|
|
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('/days/day-1'))
|
|
return jsonResponse(200, {
|
|
day: {
|
|
id: 'day-1',
|
|
date: '2026-08-24',
|
|
status: 'PLANNED',
|
|
dayOfWeek: 1,
|
|
sessions: [{ id: 'sess-1', status: 'IN_PROGRESS', startedAt: ACTIVE_SESSION.startedAt }],
|
|
},
|
|
});
|
|
if (url.includes('/sessions/sess-1'))
|
|
return jsonResponse(200, {
|
|
session: {
|
|
id: 'sess-1',
|
|
status: 'IN_PROGRESS',
|
|
startedAt: ACTIVE_SESSION.startedAt,
|
|
day: {
|
|
id: 'day-1',
|
|
date: '2026-08-24',
|
|
status: 'PLANNED',
|
|
week: { plan: { id: 'plan-1', title: 'Plan testowy', status: 'ACTIVE' } },
|
|
moveLog: [],
|
|
},
|
|
exercises: [],
|
|
},
|
|
});
|
|
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 login(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();
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
await new Promise((r) => setTimeout(r, 25));
|
|
setAccessToken(null);
|
|
localStorage.clear();
|
|
useAuth.setState({ user: null, ready: false });
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
describe('Aktywna sesja — skrót „Trening”', () => {
|
|
it('pokazuje skrót w dashboardzie i link w menu bocznym, gdy sesja trwa', async () => {
|
|
const calls = { activeSession: 0 };
|
|
mockApi(ACTIVE_SESSION, calls);
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await login(user);
|
|
|
|
// dashboard: karta „Trwa trening” ze skrótem do dnia sesji
|
|
expect(await screen.findByText('Trwa trening')).toBeInTheDocument();
|
|
const shortcut = await screen.findByRole('link', { name: /Wróć do treningu/ });
|
|
expect(shortcut).toHaveAttribute('href', '/day/day-1');
|
|
|
|
// menu boczne: link „Trening” prowadzący do dnia sesji (exact — „Wróć do treningu” to inny link)
|
|
const sidebarLink = screen.getByRole('link', { name: 'Trening', exact: true });
|
|
expect(sidebarLink).toHaveAttribute('href', '/day/day-1');
|
|
|
|
// nawigacja przez menu boczne otwiera dzień z aktywną sesją
|
|
// (tytuł PageHeader z danymi dnia — unikalny, Layout ma osobny h1 „Dzień treningowy”)
|
|
await user.click(sidebarLink);
|
|
expect(await screen.findByRole('heading', { name: 'Poniedziałek · 24.08.2026' })).toBeInTheDocument();
|
|
// pasek sesji: status + start + postęp normy
|
|
expect(await screen.findByText('W trakcie')).toBeInTheDocument();
|
|
});
|
|
|
|
it('ukrywa skrót, gdy żadna sesja nie trwa', async () => {
|
|
const calls = { activeSession: 0 };
|
|
mockApi(null, calls);
|
|
const user = userEvent.setup();
|
|
renderApp();
|
|
await login(user);
|
|
|
|
// poczekaj, aż zapytanie o aktywną sesję się zrealizuje (deterministyczny assert negatywny)
|
|
await vi.waitFor(() => expect(calls.activeSession).toBeGreaterThan(0));
|
|
expect(screen.queryByRole('link', { name: 'Trening', exact: true })).not.toBeInTheDocument();
|
|
expect(screen.queryByText('Trwa trening')).not.toBeInTheDocument();
|
|
});
|
|
});
|