import { render, screen, act, within, 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 FocusAreas from '../src/pages/catalog/FocusAreas'; import { setAccessToken } from '../src/api/client'; import { useListSearch } from '../src/store/list-search'; import { useTopbarStore } from '../src/topbar/store'; import type { FocusArea } from '../src/api/types'; const A1: FocusArea = { id: 'fa-1', name: 'Klatka piersiowa', muscle: 'chest', description: 'Wyciskanie, rozpiętki.', setsMin: 10, setsMax: 20, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', exercisesCount: 3, }; const A2: FocusArea = { id: 'fa-2', name: 'Nogi', muscle: 'legs', description: 'Przysiady, wykroki.', setsMin: null, setsMax: null, createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z', }; function jsonResponse(status: number, body: unknown) { return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' }, }); } function mockFetchSequence(...responses: Response[]) { const fetchMock = vi.fn(async () => { const next = responses.shift(); if (!next) throw new Error('No more mocked responses'); return next; }); vi.stubGlobal('fetch', fetchMock); return fetchMock; } function renderFocusAreas() { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); return render( , ); } beforeEach(() => { setAccessToken('admin-tok'); useListSearch.getState().setQuery('focus-areas', ''); }); afterEach(() => { vi.unstubAllGlobals(); }); describe('admin FocusAreas page', () => { it('lists focus areas', async () => { mockFetchSequence(jsonResponse(200, { focusAreas: [A1, A2] })); renderFocusAreas(); expect(await screen.findByText('Klatka piersiowa')).toBeInTheDocument(); expect(screen.getByText('Nogi')).toBeInTheDocument(); }); it('filters focus areas by the search box', async () => { mockFetchSequence(jsonResponse(200, { focusAreas: [A1, A2] })); renderFocusAreas(); await screen.findByText('Klatka piersiowa'); // wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store act(() => useListSearch.getState().setQuery('focus-areas', 'nogi')); expect(screen.queryByText('Klatka piersiowa')).not.toBeInTheDocument(); expect(screen.getByText('Nogi')).toBeInTheDocument(); }); it('pokazuje licznik ćwiczeń na karcie obszaru', async () => { mockFetchSequence(jsonResponse(200, { focusAreas: [A1, A2] })); renderFocusAreas(); await screen.findByText('Klatka piersiowa'); expect(screen.getByText('3 ćwiczeń')).toBeInTheDocument(); }); it('blokuje zapis, gdy setsMin > setsMax', async () => { const requests: { method: string; url: string; body: unknown }[] = []; vi.stubGlobal( 'fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input); const method = init?.method || 'GET'; if (method !== 'GET') requests.push({ method, url, body: init?.body ? JSON.parse(String(init.body)) : undefined }); if (url.includes('/admin/focus-areas') && method === 'GET') { return jsonResponse(200, { focusAreas: [A1, A2] }); } return jsonResponse(201, { focusArea: { id: 'fa-new' } }); }), ); const user = userEvent.setup(); renderFocusAreas(); await screen.findByText('Klatka piersiowa'); const action = useTopbarStore.getState().config?.actions?.find((a) => a.label === 'Nowy obszar'); action!.onClick!(); const dialog = await screen.findByRole('dialog'); await user.type(within(dialog).getByPlaceholderText('np. Klatka piersiowa'), 'Barki'); await user.type(within(dialog).getByPlaceholderText('np. chest'), 'delts'); await user.type(within(dialog).getByPlaceholderText('np. 10'), '20'); await user.type(within(dialog).getByPlaceholderText('np. 20'), '10'); await user.click(within(dialog).getByRole('button', { name: 'Dodaj' })); expect(await screen.findByText('Minimalna liczba serii musi być mniejsza lub równa maksymalnej.')).toBeInTheDocument(); expect(requests.some((r) => r.method === 'POST')).toBe(false); }); it('zmiana klucza mięśnia przy używanych ćwiczeniach wymaga potwierdzenia', async () => { const requests: { method: string; url: string; body: unknown }[] = []; vi.stubGlobal( 'fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input); const method = init?.method || 'GET'; if (method !== 'GET') requests.push({ method, url, body: init?.body ? JSON.parse(String(init.body)) : undefined }); if (url.includes('/admin/focus-areas') && method === 'GET') { return jsonResponse(200, { focusAreas: [A1, A2] }); } return jsonResponse(200, { focusArea: A1 }); }), ); const user = userEvent.setup(); renderFocusAreas(); await screen.findByText('Klatka piersiowa'); await user.click(screen.getByRole('button', { name: 'Edytuj Klatka piersiowa' })); const dialog = await screen.findByRole('dialog'); const muscleInput = within(dialog).getByPlaceholderText('np. chest'); await user.clear(muscleInput); await user.type(muscleInput, 'pecs'); await user.click(within(dialog).getByRole('button', { name: 'Zapisz' })); const confirmText = await screen.findByText('Zmieniasz klucz mięśnia'); expect(requests.some((r) => r.method === 'PATCH')).toBe(false); const confirmDialog = confirmText.closest('[role="dialog"]') as HTMLElement; await user.click(within(confirmDialog).getByRole('button', { name: 'Zapisz' })); await waitFor(() => { const patch = requests.find((r) => r.method === 'PATCH'); expect(patch?.body).toMatchObject({ muscle: 'pecs' }); }); }); });