Files
FitOS/app/test/Plans.test.tsx

159 lines
5.1 KiB
TypeScript
Raw Normal View History

import { render, screen } 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 App from '../src/App';
import { useAuth } from '../src/store/auth';
import { setAccessToken } from '../src/api/client';
import type { User, Plan } from '../src/api/types';
const USER: User = {
id: 'u1',
email: 'jan@test.local',
firstName: 'Jan',
lastName: 'Kowalski',
age: 30,
heightCm: 180,
phone: '+48 600 000 000',
isAdmin: false,
availability: null,
priorities: null,
exclusions: null,
developMuscles: [],
canDoMuscles: [],
difficultMuscles: [],
avoidMuscles: [],
createdAt: '2026-08-22T10:00:00.000Z',
};
const PLANS: Plan[] = [
{
id: 'plan-1',
userId: 'u1',
title: 'Plan masowy',
status: 'ACTIVE',
weeksCount: 8,
startDate: '2026-08-24',
weeks: [],
},
{
id: 'plan-2',
userId: 'u1',
title: 'Szkic siłowy',
status: 'DRAFT',
weeksCount: 4,
startDate: null,
weeks: [],
},
{
id: 'plan-3',
userId: 'u1',
title: 'Plan definicyjny',
status: 'COMPLETED',
weeksCount: 6,
startDate: '2026-06-01',
weeks: [],
},
];
function jsonResponse(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
}
function mockApi(plans: Plan[] = PLANS) {
vi.stubGlobal(
'fetch',
vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes('/auth/login')) return jsonResponse(200, { user: USER, accessToken: 'tok-1' });
if (url.includes('/me')) return jsonResponse(200, { user: USER, memberships: [] });
if (url.includes('/dashboard'))
return jsonResponse(200, { killstreak: 0, activePlan: null, nextTraining: null, progress: null });
if (url.includes('/exercises')) return jsonResponse(200, { exercises: [] });
if (url.includes('/plans/shared-with-me')) return jsonResponse(200, { plans: [] });
if (url.includes('/plans')) return jsonResponse(200, { plans });
if (url.includes('/calendar')) return jsonResponse(200, { month: '2026-08', days: [] });
return jsonResponse(404, { error: { code: 'NOT_FOUND', message: 'not found' } });
}),
);
}
function renderApp() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: 0, refetchOnWindowFocus: false } },
});
render(
<QueryClientProvider client={queryClient}>
<MemoryRouter initialEntries={['/']}>
<App />
</MemoryRouter>
</QueryClientProvider>,
);
}
async function openPlans(user: userEvent.User) {
expect(await screen.findByRole('heading', { name: 'FitOS' })).toBeInTheDocument();
const email = document.querySelector('input[type="email"]') as HTMLInputElement;
const password = document.querySelector('input[type="password"]') as HTMLInputElement;
await user.type(email, 'jan@test.local');
await user.type(password, 'Password123!');
await user.click(screen.getByRole('button', { name: 'Zaloguj' }));
expect(await screen.findByRole('heading', { name: 'Dashboard' })).toBeInTheDocument();
await user.click(screen.getByRole('link', { name: 'Plany' }));
expect(await screen.findByRole('heading', { name: 'Plany' })).toBeInTheDocument();
}
beforeEach(() => {
setAccessToken(null);
useAuth.setState({ user: null, ready: false });
});
afterEach(() => {
vi.unstubAllGlobals();
useAuth.setState({ user: null, ready: false });
});
describe('Lista planów', () => {
it('grupuje plany według statusu w sekcje z licznikiem', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
// sekcje kategorii (statusów) z licznikami
expect(screen.getByRole('heading', { name: 'Aktywny' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Szkic' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Ukończony' })).toBeInTheDocument();
// kategoria bez planów nie jest renderowana
expect(screen.queryByRole('heading', { name: 'Porzucony' })).not.toBeInTheDocument();
});
it('każdy kafelek jest linkiem otwierającym szczegóły planu', async () => {
mockApi();
const user = userEvent.setup();
renderApp();
await openPlans(user);
// kafelek = link o href /plans/{id} (pełni funkcję przycisku „otwórz”)
const tile = screen.getByRole('link', { name: /Plan masowy/ });
expect(tile).toHaveAttribute('href', '/plans/plan-1');
expect(tile).toHaveTextContent('Otwórz');
expect(tile).toHaveTextContent('8 tyg.');
});
it('pusty stan pokazuje komunikat i akcję „Nowy plan”', async () => {
mockApi([]);
const user = userEvent.setup();
renderApp();
await openPlans(user);
expect(screen.getByRole('heading', { name: 'Brak planów' })).toBeInTheDocument();
// akcja „Nowy plan” w topbarze i w pustym stanie
expect(screen.getAllByRole('button', { name: 'Nowy plan' }).length).toBeGreaterThan(0);
});
});