366 lines
14 KiB
TypeScript
366 lines
14 KiB
TypeScript
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 { ActivePresence, User } from '../src/api/types';
|
|
import GymQrModal from '../src/components/gyms/GymQrModal';
|
|
import StartTrainingPresenceModal from '../src/components/presence/StartTrainingPresenceModal';
|
|
import { PresenceKeepAliveModal } from '../src/components/presence/PresenceKeepAliveModal';
|
|
|
|
// QR generowany przez stub — w jsdom canvas może być niedostępny
|
|
vi.mock('qrcode', () => ({
|
|
toDataURL: vi.fn(async () => 'data:image/png;base64,MOCK'),
|
|
}));
|
|
|
|
const USER: User = {
|
|
id: 'u1',
|
|
email: 'jan@test.local',
|
|
firstName: 'Jan',
|
|
lastName: 'Kowalski',
|
|
birthDate: '1996-05-05T00:00:00.000Z',
|
|
heightCm: 180,
|
|
phone: null,
|
|
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 presence(gymId: string, gymName: string, idleMinutes = 0): ActivePresence {
|
|
// świeże znaczniki czasu — inaczej globalny modal keep-alive (Layout)
|
|
// wyskakiwałby w testach razem z upływem czasu rzeczywistego
|
|
const checkedInAt = new Date(Date.now() - (idleMinutes + 15) * 60_000).toISOString();
|
|
const lastActivityAt = new Date(Date.now() - idleMinutes * 60_000).toISOString();
|
|
return {
|
|
id: 'p1',
|
|
gymId,
|
|
gymName,
|
|
gymCapacity: 50,
|
|
status: 'ACTIVE',
|
|
source: 'MANUAL',
|
|
checkedInAt,
|
|
lastActivityAt,
|
|
closedAt: null,
|
|
};
|
|
}
|
|
|
|
function gymBody(kind: 'REAL' | 'VIRTUAL' = 'REAL') {
|
|
return {
|
|
gym: {
|
|
id: 'gym-1',
|
|
name: 'Żelazna Świątynia',
|
|
location: 'Warszawa',
|
|
availability: null,
|
|
capacity: 50,
|
|
kind,
|
|
isPrivate: false,
|
|
equipment: [],
|
|
coverPhoto: null,
|
|
photos: [],
|
|
currentOccupancy: kind === 'REAL' ? 3 : null,
|
|
},
|
|
roles: ['MEMBER'],
|
|
isAdmin: false,
|
|
};
|
|
}
|
|
|
|
interface StubOpts {
|
|
presence?: ActivePresence | null;
|
|
gymKind?: 'REAL' | 'VIRTUAL';
|
|
}
|
|
|
|
function mockApi(opts: StubOpts = {}) {
|
|
let current = opts.presence ?? null;
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = String(input);
|
|
const method = init?.method || 'GET';
|
|
if (url.includes('/auth/refresh'))
|
|
return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } });
|
|
if (url.includes('/auth/login'))
|
|
return jsonResponse(200, { user: USER, accessToken: 'tok-1' });
|
|
if (url.includes('/me/presence/history')) return jsonResponse(200, { visits: [] });
|
|
if (url.includes('/me/presence/stats'))
|
|
return jsonResponse(200, {
|
|
stats: {
|
|
visits: 0,
|
|
avgStayMinutes: null,
|
|
heatmap: [],
|
|
topGyms: [],
|
|
peak: 0,
|
|
topEquipment: [],
|
|
},
|
|
});
|
|
if (url.includes('/me/presence/check-out') && method === 'POST') {
|
|
current = null;
|
|
return jsonResponse(200, { checkedOut: true });
|
|
}
|
|
if (url.includes('/me/presence/heartbeat') && method === 'POST')
|
|
return jsonResponse(200, { touched: current != null });
|
|
if (url.includes('/me/presence')) return jsonResponse(200, { presence: current });
|
|
if (url.includes('/gyms/gym-1/check-in') && method === 'POST') {
|
|
current = presence('gym-1', 'Żelazna Świątynia');
|
|
return jsonResponse(201, { presence: current });
|
|
}
|
|
if (url.includes('/gyms/gym-1')) return jsonResponse(200, gymBody(opts.gymKind ?? 'REAL'));
|
|
if (url.includes('/me/active-session')) return jsonResponse(200, { session: null });
|
|
if (url.includes('/me/feed/unread-count')) return jsonResponse(200, { count: 0 });
|
|
if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
|
|
if (url.includes('/gyms/invitations')) return jsonResponse(200, { invitations: [] });
|
|
if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] });
|
|
if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] });
|
|
if (url.includes('/dashboard'))
|
|
return jsonResponse(200, {
|
|
killstreak: 0,
|
|
activePlan: null,
|
|
nextTraining: null,
|
|
progress: null,
|
|
});
|
|
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
|
|
}),
|
|
);
|
|
}
|
|
|
|
// logowanie przez formularz z powrotem na stronę z ?next= (deep-link QR)
|
|
async function loginTo(tester: ReturnType<typeof userEvent.setup>, next: string) {
|
|
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 tester.type(email, 'jan@test.local');
|
|
await tester.type(password, 'Password123!');
|
|
await tester.click(screen.getByRole('button', { name: 'Zaloguj' }));
|
|
if (next.includes('checkin')) {
|
|
// treść strony = karta siłowni (h2 z nazwą); topbar w unitach nie jest źródłem asercji
|
|
expect(
|
|
await screen.findByRole('heading', { name: 'Żelazna Świątynia', level: 2 }),
|
|
).toBeInTheDocument();
|
|
} else {
|
|
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
|
|
}
|
|
}
|
|
|
|
function renderAt(path: string) {
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
|
});
|
|
render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<MemoryRouter initialEntries={[path]}>
|
|
<App />
|
|
</MemoryRouter>
|
|
</QueryClientProvider>,
|
|
);
|
|
}
|
|
|
|
function renderIsolated(ui: React.ReactElement) {
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
|
|
});
|
|
render(
|
|
<QueryClientProvider client={queryClient}>
|
|
<MemoryRouter>{ui}</MemoryRouter>
|
|
</QueryClientProvider>,
|
|
);
|
|
}
|
|
|
|
beforeEach(() => {
|
|
setAccessToken(null);
|
|
localStorage.clear();
|
|
useAuth.setState({ user: null, ready: false });
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
describe('Strona check-inu (deep-link QR)', () => {
|
|
it('bez meldunku: CTA „Idę ćwiczyć” → stan zameldowany', async () => {
|
|
mockApi({ presence: null });
|
|
const tester = userEvent.setup();
|
|
renderAt(`/login?next=${encodeURIComponent('/gyms/gym-1/checkin')}`);
|
|
await loginTo(tester, '/gyms/gym-1/checkin');
|
|
|
|
expect(await screen.findByText(/Zamelduj się przed treningiem/)).toBeInTheDocument();
|
|
await tester.click(screen.getByRole('button', { name: 'Idę ćwiczyć' }));
|
|
|
|
expect(await screen.findByText('Zameldowany — udanego treningu')).toBeInTheDocument();
|
|
expect(await screen.findByRole('button', { name: 'Wychodzę' })).toBeInTheDocument();
|
|
});
|
|
|
|
it('meldunek w innej siłowni: komunikat + „Przepnij na tę siłownię”', async () => {
|
|
mockApi({ presence: presence('gym-9', 'Inna Siłownia') });
|
|
const tester = userEvent.setup();
|
|
renderAt(`/login?next=${encodeURIComponent('/gyms/gym-1/checkin')}`);
|
|
await loginTo(tester, '/gyms/gym-1/checkin');
|
|
|
|
expect(
|
|
await screen.findByText('Jesteś zameldowany w siłowni Inna Siłownia.'),
|
|
).toBeInTheDocument();
|
|
await tester.click(screen.getByRole('button', { name: 'Przepnij na tę siłownię' }));
|
|
expect(await screen.findByText('Zameldowany w Żelazna Świątynia')).toBeInTheDocument();
|
|
});
|
|
|
|
it('siłownia wirtualna: brak meldunku — komunikat', async () => {
|
|
mockApi({ presence: null, gymKind: 'VIRTUAL' });
|
|
const tester = userEvent.setup();
|
|
renderAt(`/login?next=${encodeURIComponent('/gyms/gym-1/checkin')}`);
|
|
await loginTo(tester, '/gyms/gym-1/checkin');
|
|
|
|
expect(await screen.findByText(/To wirtualna siłownia/)).toBeInTheDocument();
|
|
expect(screen.queryByRole('button', { name: 'Idę ćwiczyć' })).not.toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
describe('Modal kodu QR', () => {
|
|
it('renderuje wygenerowany obraz QR', async () => {
|
|
renderIsolated(
|
|
<GymQrModal open onClose={() => undefined} gymId="gym-1" gymName="Żelazna Świątynia" />,
|
|
);
|
|
expect(await screen.findByRole('img', { name: 'Żelazna Świątynia' })).toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
describe('Modal rozpoczęcia treningu', () => {
|
|
it('mismatch: oferuje zmianę siłowni planu na siłownię meldunku', async () => {
|
|
const onChangePlanGym = vi.fn();
|
|
renderIsolated(
|
|
<StartTrainingPresenceModal
|
|
open
|
|
onClose={() => undefined}
|
|
planGym={{ id: 'gym-1', name: 'Żelazna Świątynia' }}
|
|
presence={presence('gym-2', 'Mega Gym')}
|
|
gyms={[]}
|
|
onCheckIn={vi.fn()}
|
|
onChangePlanGym={onChangePlanGym}
|
|
onContinue={vi.fn()}
|
|
/>,
|
|
);
|
|
const tester = userEvent.setup();
|
|
await tester.click(
|
|
await screen.findByRole('button', { name: 'Zmień siłownię planu na Mega Gym' }),
|
|
);
|
|
expect(onChangePlanGym).toHaveBeenCalledWith('gym-2');
|
|
});
|
|
|
|
it('brak meldunku: „Melduję się” melduje w siłowni planu', async () => {
|
|
const onCheckIn = vi.fn();
|
|
renderIsolated(
|
|
<StartTrainingPresenceModal
|
|
open
|
|
onClose={() => undefined}
|
|
planGym={{ id: 'gym-1', name: 'Żelazna Świątynia' }}
|
|
presence={null}
|
|
gyms={[]}
|
|
onCheckIn={onCheckIn}
|
|
onChangePlanGym={vi.fn()}
|
|
onContinue={vi.fn()}
|
|
/>,
|
|
);
|
|
const tester = userEvent.setup();
|
|
await tester.click(await screen.findByRole('button', { name: 'Melduję się' }));
|
|
expect(onCheckIn).toHaveBeenCalledWith('gym-1');
|
|
});
|
|
|
|
it('brak meldunku: „Kontynuuj bez meldunku” startuje bez meldunku', async () => {
|
|
const onContinue = vi.fn();
|
|
renderIsolated(
|
|
<StartTrainingPresenceModal
|
|
open
|
|
onClose={() => undefined}
|
|
planGym={{ id: 'gym-1', name: 'Żelazna Świątynia' }}
|
|
presence={null}
|
|
gyms={[]}
|
|
onCheckIn={vi.fn()}
|
|
onChangePlanGym={vi.fn()}
|
|
onContinue={onContinue}
|
|
/>,
|
|
);
|
|
const tester = userEvent.setup();
|
|
await tester.click(await screen.findByRole('button', { name: 'Kontynuuj bez meldunku' }));
|
|
expect(onContinue).toHaveBeenCalled();
|
|
});
|
|
});
|
|
|
|
describe('Globalny modal keep-alive bytności', () => {
|
|
function stubPresenceFetch(initial: ActivePresence | null) {
|
|
let current = initial;
|
|
const calls: { url: string; method: string }[] = [];
|
|
vi.stubGlobal(
|
|
'fetch',
|
|
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const url = String(input);
|
|
const method = init?.method || 'GET';
|
|
calls.push({ url, method });
|
|
if (url.includes('/me/presence/heartbeat') && method === 'POST') {
|
|
if (current) current = { ...current, lastActivityAt: new Date().toISOString() };
|
|
return jsonResponse(200, { touched: current != null });
|
|
}
|
|
if (url.includes('/me/presence/check-out') && method === 'POST') {
|
|
current = null;
|
|
return jsonResponse(200, { checkedOut: true });
|
|
}
|
|
if (url.includes('/me/presence')) return jsonResponse(200, { presence: current });
|
|
throw new Error(`Unexpected fetch: ${url}`);
|
|
}),
|
|
);
|
|
return calls;
|
|
}
|
|
|
|
it('po 20+ min bez aktywności modal wyskakuje sam, „Wciąż tu jestem” odświeża i zamyka', async () => {
|
|
setAccessToken('tok-1');
|
|
const calls = stubPresenceFetch(presence('gym-1', 'Żelazna Świątynia', 25));
|
|
renderIsolated(<PresenceKeepAliveModal />);
|
|
|
|
expect(await screen.findByText('Nadal jesteś na siłowni?')).toBeInTheDocument();
|
|
expect(screen.getByText(/Żelazna Świątynia/)).toBeInTheDocument();
|
|
|
|
const tester = userEvent.setup();
|
|
await tester.click(screen.getByRole('button', { name: 'Wciąż tu jestem' }));
|
|
await waitFor(() =>
|
|
expect(screen.queryByText('Nadal jesteś na siłowni?')).not.toBeInTheDocument(),
|
|
);
|
|
expect(calls.some((c) => c.method === 'POST' && c.url.includes('heartbeat'))).toBe(true);
|
|
});
|
|
|
|
it('„Wychodzę” wymeldowuje i zamyka modal', async () => {
|
|
setAccessToken('tok-1');
|
|
const calls = stubPresenceFetch(presence('gym-1', 'Żelazna Świątynia', 25));
|
|
renderIsolated(<PresenceKeepAliveModal />);
|
|
|
|
expect(await screen.findByText('Nadal jesteś na siłowni?')).toBeInTheDocument();
|
|
const tester = userEvent.setup();
|
|
await tester.click(screen.getByRole('button', { name: 'Wychodzę' }));
|
|
await waitFor(() =>
|
|
expect(screen.queryByText('Nadal jesteś na siłowni?')).not.toBeInTheDocument(),
|
|
);
|
|
expect(calls.some((c) => c.method === 'POST' && c.url.includes('check-out'))).toBe(true);
|
|
});
|
|
|
|
it('świeży meldunek (<20 min aktywności): modal się nie pokazuje', async () => {
|
|
setAccessToken('tok-1');
|
|
const calls = stubPresenceFetch(presence('gym-1', 'Żelazna Świątynia', 5));
|
|
renderIsolated(<PresenceKeepAliveModal />);
|
|
|
|
// czekamy aż zapytanie o bytność realnie się wykona, potem brak modala
|
|
await waitFor(() => expect(calls.some((c) => c.url.includes('/me/presence'))).toBe(true));
|
|
expect(screen.queryByText('Nadal jesteś na siłowni?')).not.toBeInTheDocument();
|
|
});
|
|
});
|