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, Message } from '../src/api/types'; const TRAINER: User = { id: 'trainer-1', email: 'trener@test.local', firstName: 'Marek', lastName: 'Trener', age: 35, heightCm: 185, phone: null, isAdmin: false, availability: null, priorities: null, exclusions: null, developMuscles: [], canDoMuscles: [], difficultMuscles: [], avoidMuscles: [], createdAt: '2026-01-01T00:00:00.000Z', }; const BASE_MESSAGES: Message[] = [ { id: 'msg-1', senderId: 'trainee-1', body: 'Dobrze się czuję', createdAt: '2026-08-24T10:00:00.000Z', attachment: null, }, ]; const TRAINEE_HISTORY = { sessions: [ { id: 'hist-1', status: 'COMPLETED', startedAt: '2026-08-24T07:00:00.000Z', endedAt: '2026-08-24T08:30:00.000Z', date: '2026-08-24', dayOfWeek: 1, plan: 'Plan testowy', norm: { done: 1, total: 1 }, bonus: 0, deficit: 0, exercises: [ { id: 'se-1', name: 'Przysiady', muscle: 'legs', isExtra: false, comments: [], sets: [{ index: 0, reps: 10, rir: 2, difficulty: 3, planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } }], }, { id: 'se-2', name: 'Wyciskanie', muscle: 'chest', isExtra: true, comments: [], sets: [{ index: 0, reps: 8, rir: 1, difficulty: null, planned: null }], }, ], }, ], }; function jsonResponse(status: number, body: unknown) { if (status === 204) return new Response(null, { status }); return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' }, }); } function mockApi() { const sent: Message[] = []; 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: TRAINER, accessToken: 'tok-1' }); if (url.includes('/auth/refresh')) return jsonResponse(401, { error: { code: 'UNAUTHORIZED', message: 'no cookie' } }); if (url.includes('/messages/conversations/coaching-1')) { if (method === 'POST') { const body = JSON.parse(String(init?.body)) as { body: string; sessionId?: string; sessionExerciseId?: string; }; const attachment = body.sessionId ? body.sessionExerciseId ? { sessionId: body.sessionId, sessionDate: '2026-08-24', plan: 'Plan testowy', exercise: { name: 'Przysiady', sets: [{ index: 0, reps: 10, rir: 2, planned: { reps: 10, loadKg: 60, restSec: 90, rir: 2 } }], }, exercises: [], } : { sessionId: body.sessionId, sessionDate: '2026-08-24', plan: 'Plan testowy', exercise: null, exercises: [ { name: 'Przysiady', setsDone: 1, setsTotal: 1 }, { name: 'Wyciskanie', setsDone: 1, setsTotal: 1 }, ], } : null; const msg: Message = { id: `sent-${sent.length}`, senderId: TRAINER.id, body: body.body, createdAt: new Date().toISOString(), attachment, }; sent.push(msg); return jsonResponse(201, { message: msg }); } return jsonResponse(200, { role: 'trainer', other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak' }, messages: [...BASE_MESSAGES, ...sent], }); } if (url.includes('/messages/conversations')) return jsonResponse(200, { conversations: [ { coachingId: 'coaching-1', role: 'trainer', other: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak' }, lastMessage: { body: 'Dobrze się czuję', createdAt: '2026-08-24T10:00:00.000Z', senderId: 'trainee-1' }, unreadCount: 0, }, ], }); if (url.includes('/trainer/trainees/trainee-1/history')) return jsonResponse(200, TRAINEE_HISTORY); if (url.includes('/trainer/trainees/trainee-1')) return jsonResponse(200, { coachingId: 'coaching-1', user: { id: 'trainee-1', firstName: 'Anna', lastName: 'Nowak', nickname: null }, socialMedia: null, gyms: [{ id: 'gym-1', name: 'Żelazna Świątynia' }], activePlan: { id: 'plan-1', title: 'Plan testowy', startDate: '2026-08-01' }, progress: { completed: 5, total: 14, percent: 36 }, killstreak: 3, nextTraining: { dayId: 'day-1', date: '2026-08-26', exercises: [{ name: 'Przysiady', muscle: 'legs' }] }, extra: null, missing: null, lastSessionAt: '2026-08-24T08:30:00.000Z', flags: ['no_session_7d'], }); if (url.includes('/me/history')) return jsonResponse(200, { sessions: [] }); if (url.includes('/me')) return jsonResponse(200, { user: TRAINER, memberships: [] }); if (url.includes('/dashboard')) return jsonResponse(200, { killstreak: 0, activePlan: null, nextTraining: null, progress: null }); if (url.includes('/trainer/trainees')) return jsonResponse(200, { trainees: [] }); if (url.includes('/trainer/invitations')) return jsonResponse(200, { invitations: [] }); if (url.includes('/gyms/invitations')) return jsonResponse(200, { invitations: [] }); if (url.includes('/me/active-session')) return jsonResponse(200, { session: null }); if (url.includes('/gyms')) return jsonResponse(200, { gyms: [] }); if (url.includes('/exercises')) return jsonResponse(200, { exercises: [] }); if (url.includes('/plans')) return jsonResponse(200, { plans: [] }); if (url.includes('/calendar')) return jsonResponse(200, { month: '2026-08', days: [] }); return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } }); }), ); } async function loginToThread(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, 'trener@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: /Komunikator/ })); await user.click(await screen.findByRole('button', { name: /Anna Nowak/ })); expect(await screen.findByRole('heading', { name: 'Anna Nowak' })).toBeInTheDocument(); } function renderApp() { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } }, }); return render( , ); } beforeEach(async () => { await new Promise((r) => setTimeout(r, 25)); setAccessToken(null); localStorage.clear(); useAuth.setState({ user: null, ready: false }); }); afterEach(() => { vi.unstubAllGlobals(); }); describe('Message thread — wątek', () => { it('pokazuje wiadomości i nazwę drugiej strony', async () => { mockApi(); const user = userEvent.setup(); renderApp(); await loginToThread(user); expect(screen.getByText('Dobrze się czuję')).toBeInTheDocument(); }); it('pokazuje kartę kontekstu treningowego podopiecznego i akcję „Otwórz panel podopiecznego”', async () => { mockApi(); const user = userEvent.setup(); renderApp(); await loginToThread(user); // karta kontekstu: sekcja + plan + flaga + killstreak expect(await screen.findByText('Trening podopiecznego')).toBeInTheDocument(); expect(screen.getByText('Plan testowy')).toBeInTheDocument(); expect(screen.getByText('Brak sesji 7 dni')).toBeInTheDocument(); expect(screen.getByText('3')).toBeInTheDocument(); // mostek do kokpitu treningowego (grupa Akcje w topmenu) const openPanel = screen.getByRole('button', { name: 'Otwórz panel podopiecznego' }); expect(openPanel).toBeInTheDocument(); await user.click(openPanel); // lądowanie w panelu podopiecznego (zakładka Przegląd) expect(await screen.findByRole('heading', { name: 'Anna Nowak' })).toBeInTheDocument(); expect(screen.getByText('Podstawowe informacje')).toBeInTheDocument(); }); it('wysyła wiadomość (Wyślij)', async () => { mockApi(); const user = userEvent.setup(); renderApp(); await loginToThread(user); await user.type(screen.getByRole('textbox', { name: 'Treść wiadomości' }), 'Cześć Anno'); await user.click(screen.getByRole('button', { name: /Wyślij/ })); // po wysłaniu wątek się odświeża i pokazuje nową wiadomość expect(await screen.findByText('Cześć Anno')).toBeInTheDocument(); }); it('załącza wynik sesji + ćwiczenia i wysyła z załącznikiem', async () => { mockApi(); const user = userEvent.setup(); renderApp(); await loginToThread(user); await user.type(screen.getByRole('textbox', { name: 'Treść wiadomości' }), 'Twój wynik'); await user.click(screen.getByRole('button', { name: /Załącz wynik/ })); // modal: wybór sesji, potem ćwiczenia await user.selectOptions(screen.getByRole('combobox', { name: 'Sesja' }), 'hist-1'); await user.selectOptions(await screen.findByRole('combobox', { name: 'Ćwiczenie' }), 'se-1'); await user.click(screen.getByRole('button', { name: /Dodaj załącznik/ })); // załącznik jako etap w composerze (chip nad polem wiadomości) expect(await screen.findByText('24.08.2026 · Plan testowy · Przysiady')).toBeInTheDocument(); await user.click(screen.getByRole('button', { name: /Wyślij/ })); // karta załącznika w dymce expect(await screen.findByText('Twój wynik')).toBeInTheDocument(); expect(screen.getByText('Kliknij, aby otworzyć historię')).toBeInTheDocument(); }); it('pozwala dodać załącznik przed wpisaniem treści, a treść dopisać później', async () => { mockApi(); const user = userEvent.setup(); renderApp(); await loginToThread(user); // bez tekstu: dodanie załącznika nie jest zablokowane await user.click(screen.getByRole('button', { name: /Załącz wynik/ })); await user.selectOptions(screen.getByRole('combobox', { name: 'Sesja' }), 'hist-1'); const addBtn = screen.getByRole('button', { name: /Dodaj załącznik/ }); expect(addBtn).toBeEnabled(); await user.click(addBtn); expect(await screen.findByText('24.08.2026 · Plan testowy')).toBeInTheDocument(); // treść jeszcze pusta — Wyślij pozostaje nieaktywne expect(screen.getByRole('button', { name: /Wyślij/ })).toBeDisabled(); // treść można dopisać później i wysłać razem z załącznikiem await user.type(screen.getByRole('textbox', { name: 'Treść wiadomości' }), 'Twój wynik'); await user.click(screen.getByRole('button', { name: /Wyślij/ })); expect(await screen.findByText('Twój wynik')).toBeInTheDocument(); expect(screen.getByText('Kliknij, aby otworzyć historię')).toBeInTheDocument(); }); });