157 lines
5.4 KiB
TypeScript
157 lines
5.4 KiB
TypeScript
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 Exercises from '../src/pages/catalog/Exercises';
|
|
import { setAccessToken } from '../src/api/client';
|
|
import { useListSearch } from '../src/store/list-search';
|
|
|
|
const EQUIPMENT = [
|
|
{ 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ń.' },
|
|
];
|
|
|
|
const EXERCISE = {
|
|
id: 'ex-1',
|
|
slug: 'bench-press',
|
|
name: 'Wyciskanie sztangi leżąc',
|
|
primaryMuscle: 'chest',
|
|
secondaryMuscles: ['triceps'],
|
|
equipment: [EQUIPMENT[0]],
|
|
hasReps: true,
|
|
hasLoad: true,
|
|
hasRest: true,
|
|
hasSets: true,
|
|
hasRir: true,
|
|
hasDifficulty: true,
|
|
hasCardio: false,
|
|
hasTime: false,
|
|
hasSpeed: false,
|
|
description: 'Podstawowe ćwiczenie na klatkę.',
|
|
howTo: null,
|
|
commonMistakes: null,
|
|
difficulty: 4,
|
|
source: 'BUILTIN',
|
|
};
|
|
|
|
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 = {
|
|
exercises: [{ ...EXERCISE, equipment: [{ ...EQUIPMENT[0] }] }],
|
|
equipment: EQUIPMENT.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/exercises')) {
|
|
const id = url.match(/\/admin\/exercises\/([^/]+)$/)?.[1];
|
|
if (method === 'GET') return jsonResponse(200, { exercises: state.exercises });
|
|
if (method === 'POST') {
|
|
state.exercises.push({ id: `ex-${state.exercises.length + 1}`, ...body });
|
|
return jsonResponse(201, { exercises: state.exercises });
|
|
}
|
|
if (method === 'PATCH') {
|
|
state.exercises = state.exercises.map((e) => (e.id === id ? { ...e, ...body } : e));
|
|
return jsonResponse(200, { exercises: state.exercises });
|
|
}
|
|
if (method === 'DELETE') {
|
|
state.exercises = state.exercises.filter((e) => e.id !== id);
|
|
return jsonResponse(204, {});
|
|
}
|
|
}
|
|
if (url.includes('/admin/equipment')) {
|
|
if (method === 'GET') return jsonResponse(200, { equipment: state.equipment });
|
|
}
|
|
return jsonResponse(404, { error: { message: 'not found' } });
|
|
}),
|
|
);
|
|
return { requests };
|
|
}
|
|
|
|
function renderExercises() {
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
|
|
});
|
|
return render(
|
|
<MemoryRouter initialEntries={['/exercises']}>
|
|
<QueryClientProvider client={queryClient}>
|
|
<Routes>
|
|
<Route path="/exercises" element={<Exercises />} />
|
|
</Routes>
|
|
</QueryClientProvider>
|
|
</MemoryRouter>,
|
|
);
|
|
}
|
|
|
|
beforeEach(() => {
|
|
setAccessToken('admin-tok');
|
|
useListSearch.getState().setQuery('exercises', '');
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
describe('admin Exercises page', () => {
|
|
it('renderuje listę ćwiczeń z mięśniami i przypisanymi maszynami', async () => {
|
|
mockApi();
|
|
renderExercises();
|
|
expect(await screen.findByText('Wyciskanie sztangi leżąc')).toBeInTheDocument();
|
|
expect(screen.getByText('chest')).toBeInTheDocument();
|
|
expect(screen.getByText('Sztanga')).toBeInTheDocument();
|
|
});
|
|
|
|
it('edycja ćwiczenia pozwala przypisać urządzenia i wysyła PATCH', async () => {
|
|
const { requests } = mockApi();
|
|
const user = userEvent.setup();
|
|
renderExercises();
|
|
await screen.findByText('Wyciskanie sztangi leżąc');
|
|
|
|
await user.click(screen.getByRole('button', { name: 'Edytuj Wyciskanie sztangi leżąc' }));
|
|
const dialog = await screen.findByRole('dialog');
|
|
// Sztanga (eq-1) jest już przypisane, Dywan (eq-2) nie — oznaczamy Dywan
|
|
await user.click(within(dialog).getByRole('checkbox', { name: 'Dywan' }));
|
|
await user.click(within(dialog).getByRole('button', { name: 'Zapisz' }));
|
|
|
|
await waitFor(() => {
|
|
const patch = requests.find(
|
|
(r) => r.method === 'PATCH' && r.url.includes('/admin/exercises/ex-1'),
|
|
);
|
|
expect(patch?.body).toMatchObject({
|
|
name: 'Wyciskanie sztangi leżąc',
|
|
primaryMuscle: 'chest',
|
|
equipmentIds: ['eq-1', 'eq-2'],
|
|
});
|
|
});
|
|
});
|
|
|
|
it('filters exercises by the search box', async () => {
|
|
mockApi();
|
|
renderExercises();
|
|
expect(await screen.findByText('Wyciskanie sztangi leżąc')).toBeInTheDocument();
|
|
// wyszukiwarka jest w menu kontekstowym (Layout) — filtr ustawiamy przez store
|
|
act(() => useListSearch.getState().setQuery('exercises', 'przysiad'));
|
|
expect(screen.queryByText('Wyciskanie sztangi leżąc')).not.toBeInTheDocument();
|
|
expect(screen.getByText('Brak wyników dla podanego zapytania.')).toBeInTheDocument();
|
|
});
|
|
});
|