Files
FitOS/admin/test/Equipment.test.tsx

154 lines
6.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { render, screen, waitFor, within, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import EquipmentCatalog from '../src/pages/catalog/Equipment';
import { setAccessToken } from '../src/api/client';
import { useTopbarStore } from '../src/topbar/store';
import { useListSearch } from '../src/store/list-search';
const SEED = [
{ id: 'eq-1', name: 'Sztanga', kind: 'BARBELL', spec: { maxLoadKg: 100 }, description: 'Sztanga z talerzami.' },
{ id: 'eq-2', name: 'Dywan', kind: 'OTHER', spec: null, description: 'Dywan do ćwiczeń.' },
];
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
interface Recorded {
method: string;
url: string;
body: unknown;
}
/** Stateful mock: zmiany (POST/PATCH/DELETE) są widoczne po refetchu. */
function mockApi() {
const state = { items: SEED.map((e) => ({ ...e })) };
const requests: Recorded[] = [];
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
const method = init?.method || 'GET';
const body = init?.body ? JSON.parse(String(init.body)) : undefined;
requests.push({ method, url, body });
if (url.includes('/admin/equipment')) {
const id = url.match(/\/admin\/equipment\/([^/]+)$/)?.[1];
if (method === 'GET') return jsonResponse(200, { equipment: state.items });
if (method === 'POST') {
state.items.push({ id: `eq-${state.items.length + 1}`, ...body });
return jsonResponse(201, { equipment: state.items });
}
if (method === 'PATCH') {
state.items = state.items.map((e) => (e.id === id ? { ...e, ...body } : e));
return jsonResponse(200, { equipment: state.items });
}
if (method === 'DELETE') {
state.items = state.items.filter((e) => e.id !== id);
return jsonResponse(204, {});
}
}
return jsonResponse(404, { error: { message: 'not found' } });
}),
);
return { requests };
}
function renderEquipment() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
});
return render(
<MemoryRouter initialEntries={['/equipment']}>
<QueryClientProvider client={queryClient}>
<Routes>
<Route path="/equipment" element={<EquipmentCatalog />} />
</Routes>
</QueryClientProvider>
</MemoryRouter>,
);
}
beforeEach(() => {
setAccessToken('admin-tok');
useListSearch.getState().setQuery('equipment', '');
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('admin Equipment page', () => {
it('renderuje katalog urządzeń z nazwami, opisami i specyfikacją', async () => {
mockApi();
renderEquipment();
expect(await screen.findByText('Sztanga z talerzami.')).toBeInTheDocument();
// type-specific spec summary (BARBELL → max load)
expect(screen.getByText('do 100 kg')).toBeInTheDocument();
expect(screen.getByText('Dywan do ćwiczeń.')).toBeInTheDocument();
// przycisk „Nowe urządzenie” jest w top menu (komponent Topbar), nie w treści strony
expect(screen.queryByRole('button', { name: 'Nowe urządzenie' })).not.toBeInTheDocument();
});
it('filters equipment by the search box', async () => {
mockApi();
renderEquipment();
await screen.findByText('Sztanga z talerzami.');
// wyszukiwarka jest w top menu (komponent Topbar) — filtr ustawiamy przez store
act(() => useListSearch.getState().setQuery('equipment', 'dywan'));
expect(screen.queryByText('Sztanga z talerzami.')).not.toBeInTheDocument();
expect(screen.getByText('Dywan do ćwiczeń.')).toBeInTheDocument();
});
it('dodawanie urządzenia z rodzajem i specyfikacją wysyła POST', async () => {
const { requests } = mockApi();
const user = userEvent.setup();
renderEquipment();
await screen.findByText('Sztanga z talerzami.');
// przycisk „Nowe urządzenie” jest w top menu — strona rejestruje akcję w store topbar
const topbar = useTopbarStore.getState().config;
const action = topbar?.actions?.find((a) => a.label === 'Nowe urządzenie');
expect(action?.onClick).toBeTypeOf('function');
action!.onClick!();
const dialog = await screen.findByRole('dialog');
await user.type(dialog.querySelector('input') as HTMLInputElement, 'Kettlebell');
await user.selectOptions(dialog.querySelector('select') as HTMLSelectElement, 'KETTLEBELL');
await user.type(dialog.querySelector('input[placeholder="np. 2.5"]') as HTMLInputElement, '4');
await user.type(dialog.querySelector('input[placeholder="np. 25"]') as HTMLInputElement, '32');
await user.click(within(dialog).getByRole('button', { name: 'Dodaj', exact: true }));
// the new card shows the kind label and the spec summary
await waitFor(() => expect(screen.getByText('4–32 kg')).toBeInTheDocument());
const post = requests.find((r) => r.method === 'POST' && r.url.includes('/admin/equipment'));
expect(post?.body).toMatchObject({
name: 'Kettlebell',
kind: 'KETTLEBELL',
spec: { minKg: 4, maxKg: 32 },
});
});
it('usuwanie urządzenia wysyła DELETE do API', async () => {
const { requests } = mockApi();
const user = userEvent.setup();
renderEquipment();
await screen.findByText('Sztanga z talerzami.');
await user.click(screen.getByRole('button', { name: 'Usuń Sztanga' }));
const dialog = await screen.findByRole('dialog');
await user.click(within(dialog).getByRole('button', { name: 'Usuń', exact: true }));
await waitFor(() => {
const del = requests.find(
(r) => r.method === 'DELETE' && r.url.includes('/admin/equipment/eq-1'),
);
expect(del).toBeDefined();
});
});
});