import { render, screen, act } 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 Logs from '../src/pages/Logs'; import { Topbar } from '../src/topbar'; import { setAccessToken } from '../src/api/client'; import { useListSearch } from '../src/store/list-search'; import type { ActivityLog } from '../src/api/types'; const LOG1: ActivityLog = { id: 'log-1', action: 'plan.activated', entityType: 'plan', entityId: 'plan-1', details: { actorId: 'user-1', title: 'Plan na masę', startDate: '2026-08-24' }, createdAt: '2026-08-20T10:00:00.000Z', actor: { id: 'user-1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski' }, }; const LOG2: ActivityLog = { id: 'log-2', action: 'session.completed', entityType: 'session', entityId: 'session-1', details: null, createdAt: '2026-08-21T18:30:00.000Z', actor: { id: 'user-2', email: 'anna@test.local', firstName: 'Anna', lastName: null }, }; const LOG3: ActivityLog = { id: 'log-3', action: 'weight.removed', entityType: 'user', entityId: 'user-1', details: { actorId: 'user-1', value: 82.5 }, createdAt: '2026-08-22T09:00:00.000Z', actor: { id: 'user-1', email: 'jan@test.local', firstName: 'Jan', lastName: 'Kowalski' }, }; function jsonResponse(status: number, body: unknown) { return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' }, }); } function mockFetchSequence(...responses: Response[]) { const calls: { url: string; init?: RequestInit }[] = []; const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { calls.push({ url, init }); const next = responses.shift(); if (!next) throw new Error(`No more mocked responses for url: ${url}`); return next; }); vi.stubGlobal('fetch', fetchMock); return calls; } function renderLogs() { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); return render( {/* filtry (akcja, zakres dat) są w top menu — renderujemy też Topbar */} , ); } beforeEach(() => { setAccessToken('admin-tok'); useListSearch.getState().setQuery('logs', ''); }); afterEach(() => { vi.unstubAllGlobals(); }); describe('admin Logs page', () => { it('lists activity logs fetched from the API', async () => { mockFetchSequence(jsonResponse(200, { logs: [LOG1, LOG2, LOG3], total: 3 })); renderLogs(); // teksty występujące tylko w tabeli (nie w opcjach selecta) — czekamy na dane // Jan Kowalski w dwóch wierszach (plan.activated + weight.removed) expect((await screen.findAllByText('Jan Kowalski')).length).toBe(2); expect(await screen.findByText('Plan na masę')).toBeInTheDocument(); // szczegóły jako naturalny tekst (tytuł i actorId są w innych kolumnach) expect(await screen.findByText('start: 2026-08-24')).toBeInTheDocument(); // ID aktora pod e-mailem w kolumnie „Użytkownik" expect(screen.getAllByText('user-1').length).toBeGreaterThan(0); // aktor: e-mail pod imieniem i nazwiskiem expect(screen.getByText('anna@test.local')).toBeInTheDocument(); // etykiety akcji expect(screen.getAllByText('Plan aktywowany').length).toBeGreaterThan(0); expect(screen.getAllByText('Sesja zakończona').length).toBeGreaterThan(0); // usunięcie pomiaru: etykieta PL + naturalne szczegóły z jednostką expect(screen.getAllByText('Waga usunięta').length).toBeGreaterThan(0); expect(screen.getByText('wartość: 82.5 kg')).toBeInTheDocument(); }); it('sends the action filter to the API', async () => { const calls = mockFetchSequence( jsonResponse(200, { logs: [LOG1, LOG2], total: 2 }), jsonResponse(200, { logs: [LOG2], total: 1 }), ); renderLogs(); await screen.findByText('Jan Kowalski'); // filtr akcji jest w grupie lejka (ikona „Filtry” w nagłówku) await userEvent.click(screen.getByRole('button', { name: 'Filtry' })); await userEvent.selectOptions(screen.getByRole('combobox', { name: 'Filtruj po akcji' }), 'session.completed'); // refetch z nowym queryKey — czekamy na drugi wywołany fetch await vi.waitFor(() => expect(calls.length).toBe(2)); expect(calls.at(-1)?.url).toContain('action=session.completed'); // mock filtruje po action — w tabeli zostaje tylko wpis sesji await vi.waitFor(() => expect(screen.queryByText('Plan na masę')).not.toBeInTheDocument()); }); it('sends the selected month as from/to to the API', async () => { const calls = mockFetchSequence( jsonResponse(200, { logs: [LOG1, LOG2], total: 2 }), jsonResponse(200, { logs: [LOG1], total: 1 }), jsonResponse(200, { logs: [LOG1, LOG2], total: 2 }), ); renderLogs(); await screen.findByText('Jan Kowalski'); // otwieramy grupę „Filtry”, potem panel selektora miesiąca i wybieramy sierpień bieżącego roku await userEvent.click(screen.getByRole('button', { name: 'Filtry' })); await userEvent.click(screen.getByRole('button', { name: 'Miesiąc' })); await userEvent.click(screen.getByRole('button', { name: 'Sie' })); // refetch z nowym queryKey — czekamy na drugi wywołany fetch await vi.waitFor(() => expect(calls.length).toBe(2)); const url = new URL(calls.at(-1)!.url, 'http://localhost'); expect(url.searchParams.get('from')).toBe('2026-08-01'); expect(url.searchParams.get('to')).toBe('2026-08-31'); // etykieta przycisku pokazuje wybrany miesiąc expect(screen.getByRole('button', { name: 'Sierpień 2026' })).toBeInTheDocument(); // ponowne kliknięcie zaznaczonego miesiąca odznacza filtr (brak from/to) await userEvent.click(screen.getByRole('button', { name: 'Sierpień 2026' })); await userEvent.click(screen.getByRole('button', { name: 'Sie' })); await vi.waitFor(() => expect(calls.length).toBe(3)); const url2 = new URL(calls.at(-1)!.url, 'http://localhost'); expect(url2.searchParams.get('from')).toBeNull(); expect(url2.searchParams.get('to')).toBeNull(); expect(screen.getByRole('button', { name: 'Miesiąc' })).toBeInTheDocument(); }); it('filters the loaded page by the header search box', async () => { mockFetchSequence(jsonResponse(200, { logs: [LOG1, LOG2], total: 2 })); renderLogs(); await screen.findByText('Jan Kowalski'); // wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store act(() => useListSearch.getState().setQuery('logs', 'anna')); expect(screen.queryByText('Jan Kowalski')).not.toBeInTheDocument(); expect(screen.getByText('anna@test.local')).toBeInTheDocument(); }); it('shows an error when the logs request fails', async () => { mockFetchSequence(jsonResponse(500, { error: { code: 'INTERNAL', message: 'Błąd wewnętrzny' } })); renderLogs(); expect(await screen.findByText(/Błąd: Błąd wewnętrzny/)).toBeInTheDocument(); }); it('shows an empty state when there are no logs', async () => { mockFetchSequence(jsonResponse(200, { logs: [], total: 0 })); renderLogs(); expect(await screen.findByText('Brak zdarzeń')).toBeInTheDocument(); }); });