182 lines
7.8 KiB
TypeScript
182 lines
7.8 KiB
TypeScript
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, { ACTION_KEYS } from '../src/pages/Logs';
|
|
import { Topbar } from '../src/topbar';
|
|
import { setAccessToken } from '../src/api/client';
|
|
import { useListSearch } from '../src/store/list-search';
|
|
import i18n from '../src/i18n';
|
|
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(
|
|
<MemoryRouter initialEntries={['/logs']}>
|
|
<QueryClientProvider client={queryClient}>
|
|
{/* filtry (akcja, zakres dat) są w top menu — renderujemy też Topbar */}
|
|
<Topbar />
|
|
<Logs />
|
|
</QueryClientProvider>
|
|
</MemoryRouter>,
|
|
);
|
|
}
|
|
|
|
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: 'Wszystkie' }));
|
|
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 otwarcie panelu i wybór „Wszystkie” cofa filtr miesiąca (brak from/to)
|
|
await userEvent.click(screen.getByRole('button', { name: 'Sierpień 2026' }));
|
|
await userEvent.click(screen.getByRole('button', { name: 'Wszystkie' }));
|
|
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: 'Wszystkie' })).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();
|
|
});
|
|
|
|
it('tłumaczy każdą akcję dostępną w filtrze', () => {
|
|
// strażnik spójności: każdy klucz ACTION_KEYS musi mieć etykietę PL w logs.json
|
|
for (const action of ACTION_KEYS) {
|
|
const label = i18n.t(`logs:actions.${action}`, { defaultValue: '' });
|
|
expect(label, `brak tłumaczenia akcji: ${action}`).not.toBe('');
|
|
}
|
|
});
|
|
});
|