Restructures frontend to a feature-based folder layout
Continuous Integration / config (pull_request) Successful in 11s
Continuous Integration / changes (pull_request) Successful in 21s
Continuous Integration / backend-build (pull_request) Skipped
Continuous Integration / backend-test (pull_request) Skipped
Continuous Integration / vulnerability-scan (pull_request) Skipped
Continuous Integration / frontend-prepare (pull_request) Successful in 1m37s
Continuous Integration / frontend-build (pull_request) Successful in 2m12s
Continuous Integration / frontend-test (pull_request) Successful in 4m42s
Continuous Integration / frontend-lint (pull_request) Successful in 2m2s
Continuous Integration / publish-production (pull_request) Skipped
Continuous Integration / deploy-production (pull_request) Skipped
Continuous Integration / publish-test (pull_request) Successful in 6m51s
Continuous Integration / deploy-test (pull_request) Skipped
Continuous Integration / config (pull_request) Successful in 11s
Continuous Integration / changes (pull_request) Successful in 21s
Continuous Integration / backend-build (pull_request) Skipped
Continuous Integration / backend-test (pull_request) Skipped
Continuous Integration / vulnerability-scan (pull_request) Skipped
Continuous Integration / frontend-prepare (pull_request) Successful in 1m37s
Continuous Integration / frontend-build (pull_request) Successful in 2m12s
Continuous Integration / frontend-test (pull_request) Successful in 4m42s
Continuous Integration / frontend-lint (pull_request) Successful in 2m2s
Continuous Integration / publish-production (pull_request) Skipped
Continuous Integration / deploy-production (pull_request) Skipped
Continuous Integration / publish-test (pull_request) Successful in 6m51s
Continuous Integration / deploy-test (pull_request) Skipped
Groups auth, setup, invitation, profile, users, cms, availability and system code (services/hooks, components, schemas, mocks, pages) under src/features/<name> instead of splitting by technical layer (api/, components/, lib/schemas/, mocks/, pages/). Renames the old connection-oriented `api` layer to `services` per feature, and splits the monolithic api/types.ts into per-feature types.ts files (with ProblemDetails/ApiResult merged into lib/api-client.ts as shared infra). Layout-agnostic code (ui primitives, app shell, i18n, test utils, lib) stays at the top level. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import type { SetupStatus } from '@/features/setup/services/types';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
|
||||
/** Setup status mock (used by public bootstrap guards). */
|
||||
export const setupHandlers = [
|
||||
http.get(`${API_BASE}/api/v1/Setup/status`, () =>
|
||||
HttpResponse.json<SetupStatus>({ initialized: true }),
|
||||
),
|
||||
|
||||
http.post(`${API_BASE}/api/v1/Setup/owner`, async ({ request }) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const body = await request.json() as any;
|
||||
if (!body.email || !body.password || !body.name) {
|
||||
return HttpResponse.json(
|
||||
{
|
||||
type: 'about:blank',
|
||||
title: 'Bad Request',
|
||||
status: 400,
|
||||
detail: 'Missing required fields'
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
return HttpResponse.json(
|
||||
{
|
||||
message: 'System initialized',
|
||||
user: {
|
||||
id: '1',
|
||||
name: body.name,
|
||||
email: body.email,
|
||||
role: 'Owner'
|
||||
}
|
||||
},
|
||||
{ status: 201 }
|
||||
);
|
||||
}),
|
||||
];
|
||||
|
||||
/** Override: simulates network error on setup status — backend unreachable. */
|
||||
export const setupNetworkErrorHandlers = [
|
||||
http.get(`${API_BASE}/api/v1/Setup/status`, () => HttpResponse.error()),
|
||||
];
|
||||
|
||||
/** Override: returns not-initialized status — use in tests for InitGuard. */
|
||||
export const setupUninitializedHandlers = [
|
||||
http.get(`${API_BASE}/api/v1/Setup/status`, () =>
|
||||
HttpResponse.json<SetupStatus>({ initialized: false }),
|
||||
),
|
||||
];
|
||||
|
||||
/** Override: POST /Setup/owner returns 409 — system already initialized. */
|
||||
export const setupConflictHandlers = [
|
||||
...setupUninitializedHandlers,
|
||||
http.post(`${API_BASE}/api/v1/Setup/owner`, () =>
|
||||
HttpResponse.json(
|
||||
{ title: 'Conflict', detail: 'System has already been initialized.', status: 409 },
|
||||
{ status: 409 },
|
||||
),
|
||||
),
|
||||
];
|
||||
@@ -0,0 +1,108 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { renderApp, mockGuest } from '@/test/utils';
|
||||
import { server } from '@/mocks/server';
|
||||
import { setupUninitializedHandlers, setupConflictHandlers } from '@/mocks/index';
|
||||
import { _resetSetupStatusCache } from '@/router';
|
||||
|
||||
// Each test starts with a fresh setup status cache so the MSW handler controls
|
||||
// what the InitGuard fetches (BR-U2-08).
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
});
|
||||
|
||||
describe('SetupPage', () => {
|
||||
it('renders all five form fields when system is uninitialized', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
renderApp('/setup');
|
||||
|
||||
expect(await screen.findByTestId('setup-name-input')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('setup-email-input')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('setup-password-input')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('setup-confirmPassword-input')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('setup-locale-select')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('setup-submit-button')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows inline validation errors when submitting an empty form', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/setup');
|
||||
|
||||
const submit = await screen.findByTestId('setup-submit-button');
|
||||
await user.click(submit);
|
||||
|
||||
expect(await screen.findByTestId('setup-name-error')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('setup-email-error')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('setup-password-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows password error for a weak password (no uppercase)', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/setup');
|
||||
|
||||
const passwordInput = await screen.findByTestId('setup-password-input');
|
||||
await user.type(passwordInput, 'weakpassword1!');
|
||||
await user.tab();
|
||||
|
||||
expect(await screen.findByTestId('setup-password-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows confirm-password error when passwords do not match', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/setup');
|
||||
|
||||
const passwordInput = await screen.findByTestId('setup-password-input');
|
||||
const confirmInput = screen.getByTestId('setup-confirmPassword-input');
|
||||
await user.type(passwordInput, 'ValidPass1!');
|
||||
await user.type(confirmInput, 'DifferentPass1!');
|
||||
await user.tab();
|
||||
|
||||
expect(await screen.findByTestId('setup-confirm-error')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows success message after a valid submission', async () => {
|
||||
server.use(...setupUninitializedHandlers);
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/setup');
|
||||
|
||||
await user.type(await screen.findByTestId('setup-name-input'), 'Alice Owner');
|
||||
await user.type(screen.getByTestId('setup-email-input'), 'alice@example.com');
|
||||
await user.type(screen.getByTestId('setup-password-input'), 'ValidPass1!');
|
||||
await user.type(screen.getByTestId('setup-confirmPassword-input'), 'ValidPass1!');
|
||||
await user.click(screen.getByTestId('setup-submit-button'));
|
||||
|
||||
expect(await screen.findByTestId('setup-success')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows "already initialized" banner on 409 response', async () => {
|
||||
server.use(...setupConflictHandlers);
|
||||
mockGuest();
|
||||
const user = userEvent.setup();
|
||||
renderApp('/setup');
|
||||
|
||||
await user.type(await screen.findByTestId('setup-name-input'), 'Alice Owner');
|
||||
await user.type(screen.getByTestId('setup-email-input'), 'alice@example.com');
|
||||
await user.type(screen.getByTestId('setup-password-input'), 'ValidPass1!');
|
||||
await user.type(screen.getByTestId('setup-confirmPassword-input'), 'ValidPass1!');
|
||||
await user.click(screen.getByTestId('setup-submit-button'));
|
||||
|
||||
expect(await screen.findByTestId('form-error-banner')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('redirects to /login when system is already initialized', async () => {
|
||||
// Default setupHandlers return { initialized: true } — InitGuard redirects.
|
||||
mockGuest();
|
||||
renderApp('/setup');
|
||||
|
||||
expect(await screen.findByTestId('login-form-submit-button')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import { useState } from 'react';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import { useNavigate } from '@tanstack/react-router';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { setupFormSchema, type SetupFormData } from '@/features/auth/schemas/auth';
|
||||
import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
||||
import { FieldError } from '@/components/ui/FieldError';
|
||||
import { useSetup } from '@/features/setup/services/useSetup';
|
||||
import { ProblemDetailsError, NetworkError } from '@/lib/api-client';
|
||||
import { changeLanguage } from '@/i18n/config';
|
||||
import { _markSystemInitialized } from '@/router';
|
||||
|
||||
interface FormError {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export function SetupPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const [serverError, setServerError] = useState<FormError | null>(null);
|
||||
const [successMessage, setSuccessMessage] = useState(false);
|
||||
|
||||
const setupMutation = useSetup();
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors, isSubmitting },
|
||||
control
|
||||
} = useForm<SetupFormData>({
|
||||
resolver: zodResolver(setupFormSchema),
|
||||
mode: 'onBlur',
|
||||
defaultValues: {
|
||||
name: '',
|
||||
email: '',
|
||||
password: '',
|
||||
confirmPassword: '',
|
||||
language: 'nl'
|
||||
}
|
||||
});
|
||||
|
||||
const onSubmit = handleSubmit(async (values) => {
|
||||
setServerError(null);
|
||||
try {
|
||||
const { confirmPassword: _, ...payload } = values;
|
||||
await setupMutation.mutateAsync(payload);
|
||||
await changeLanguage(values.language);
|
||||
_markSystemInitialized();
|
||||
setSuccessMessage(true);
|
||||
setTimeout(() => {
|
||||
navigate({ to: '/login' });
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
if (err instanceof ProblemDetailsError) {
|
||||
setServerError({ message: err.problem.detail || err.message || t('errors.generic') });
|
||||
} else if (err instanceof NetworkError) {
|
||||
setServerError({ message: t('errors.network') });
|
||||
} else {
|
||||
setServerError({ message: t('errors.generic') });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (successMessage) {
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4" data-testid="setup-success">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="text-green-600 text-lg font-medium">
|
||||
✓ {t('setup.successMessage')}
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('login.subtitle')}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-svh items-center justify-center bg-secondary/40 p-4">
|
||||
<Card className="w-full max-w-sm">
|
||||
<CardHeader>
|
||||
<CardTitle>{t('setup.title')}</CardTitle>
|
||||
<CardDescription>{t('login.subtitle')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} noValidate className="space-y-4" data-testid="setup-form">
|
||||
<FormErrorBanner
|
||||
error={serverError || (setupMutation.error ? { message: setupMutation.error.message } : null)}
|
||||
onDismiss={() => setServerError(null)}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="name">{t('setup.nameLabel')}</Label>
|
||||
<Input
|
||||
id="name"
|
||||
type="text"
|
||||
placeholder="John Doe"
|
||||
data-testid="setup-name-input"
|
||||
aria-invalid={errors.name !== undefined}
|
||||
{...register('name')}
|
||||
/>
|
||||
{errors.name && <FieldError message={errors.name.message} testId="setup-name-error" />}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">{t('setup.emailLabel')}</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="owner@example.com"
|
||||
data-testid="setup-email-input"
|
||||
aria-invalid={errors.email !== undefined}
|
||||
{...register('email')}
|
||||
/>
|
||||
{errors.email && <FieldError message={errors.email.message} testId="setup-email-error" />}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">{t('setup.passwordLabel')}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
data-testid="setup-password-input"
|
||||
aria-invalid={errors.password !== undefined}
|
||||
{...register('password')}
|
||||
/>
|
||||
{errors.password && <FieldError message={errors.password.message} testId="setup-password-error" />}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="confirmPassword">{t('setup.confirmPasswordLabel')}</Label>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
data-testid="setup-confirmPassword-input"
|
||||
aria-invalid={errors.confirmPassword !== undefined}
|
||||
{...register('confirmPassword')}
|
||||
/>
|
||||
{errors.confirmPassword && <FieldError message={errors.confirmPassword.message} testId="setup-confirm-error" />}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="language">{t('setup.languageLabel')}</Label>
|
||||
<Controller
|
||||
name="language"
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<select
|
||||
{...field}
|
||||
id="language"
|
||||
data-testid="setup-locale-select"
|
||||
className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||
>
|
||||
<option value="nl">Nederlands</option>
|
||||
<option value="en">English</option>
|
||||
</select>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={isSubmitting || setupMutation.isPending}
|
||||
className="w-full"
|
||||
data-testid="setup-submit-button"
|
||||
>
|
||||
{isSubmitting || setupMutation.isPending ? '...' : t('setup.submitButton')}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Setup status (used by guards during bootstrap).
|
||||
export interface SetupStatus {
|
||||
initialized: boolean;
|
||||
}
|
||||
|
||||
export interface SetupRequest {
|
||||
name: string;
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
import { useInitGuard, _resetSetupStatusCache } from '@/features/setup/services/useInitGuard';
|
||||
|
||||
const SETUP_STATUS_URL = `${API_BASE}/Setup/status`;
|
||||
|
||||
beforeEach(() => {
|
||||
_resetSetupStatusCache();
|
||||
});
|
||||
|
||||
describe('useInitGuard', () => {
|
||||
it('starts in loading state', () => {
|
||||
const { result } = renderHook(() => useInitGuard());
|
||||
|
||||
expect(result.current.isLoading).toBe(true);
|
||||
expect(result.current.initialized).toBeNull();
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
|
||||
it('returns initialized=true when system is set up', async () => {
|
||||
server.use(
|
||||
http.get(SETUP_STATUS_URL, () => HttpResponse.json({ initialized: true })),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useInitGuard());
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
expect(result.current.initialized).toBe(true);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
|
||||
it('returns initialized=false when system is not yet set up', async () => {
|
||||
server.use(
|
||||
http.get(SETUP_STATUS_URL, () => HttpResponse.json({ initialized: false })),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useInitGuard());
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
expect(result.current.initialized).toBe(false);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
|
||||
it('sets error when the API request fails', async () => {
|
||||
server.use(http.get(SETUP_STATUS_URL, () => HttpResponse.error()));
|
||||
|
||||
const { result } = renderHook(() => useInitGuard());
|
||||
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false));
|
||||
|
||||
expect(result.current.error).not.toBeNull();
|
||||
expect(result.current.initialized).toBeNull();
|
||||
});
|
||||
|
||||
it('uses cached result on second call without re-fetching', async () => {
|
||||
let callCount = 0;
|
||||
server.use(
|
||||
http.get(SETUP_STATUS_URL, () => {
|
||||
callCount += 1;
|
||||
return HttpResponse.json({ initialized: true });
|
||||
}),
|
||||
);
|
||||
|
||||
const { result: first } = renderHook(() => useInitGuard());
|
||||
await waitFor(() => expect(first.current.isLoading).toBe(false));
|
||||
|
||||
const { result: second } = renderHook(() => useInitGuard());
|
||||
await waitFor(() => expect(second.current.isLoading).toBe(false));
|
||||
|
||||
expect(callCount).toBe(1); // Only one fetch due to cache
|
||||
expect(second.current.initialized).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { api } from '@/lib/api-client';
|
||||
|
||||
interface SetupStatus {
|
||||
initialized: boolean;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
let _setupStatusCache: SetupStatus | null = null;
|
||||
let _setupStatusPromise: Promise<SetupStatus> | null = null;
|
||||
|
||||
export function useInitGuard() {
|
||||
const [initialized, setInitialized] = useState<boolean | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSetupStatus = async () => {
|
||||
if (_setupStatusCache !== null) {
|
||||
setInitialized(_setupStatusCache.initialized);
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_setupStatusPromise === null) {
|
||||
_setupStatusPromise = api
|
||||
.get<SetupStatus>('/Setup/status')
|
||||
.then((s) => {
|
||||
_setupStatusCache = s;
|
||||
return s;
|
||||
})
|
||||
.catch((err) => {
|
||||
_setupStatusPromise = null;
|
||||
throw err;
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await _setupStatusPromise;
|
||||
setInitialized(status.initialized);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err : new Error(String(err)));
|
||||
setInitialized(null);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchSetupStatus();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
initialized,
|
||||
isLoading,
|
||||
error
|
||||
};
|
||||
}
|
||||
|
||||
export function _resetSetupStatusCache(): void {
|
||||
_setupStatusCache = null;
|
||||
_setupStatusPromise = null;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { http, HttpResponse } from 'msw';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { server } from '@/mocks/server';
|
||||
import { API_BASE } from '@/features/auth/mocks/fixtures';
|
||||
import { useSetup } from '@/features/setup/services/useSetup';
|
||||
|
||||
const validSetupData = {
|
||||
name: 'Test Owner',
|
||||
email: 'owner@example.com',
|
||||
password: 'Password1!',
|
||||
language: 'nl' as const,
|
||||
};
|
||||
|
||||
describe('useSetup', () => {
|
||||
it('starts with isPending=false and no error', () => {
|
||||
const { result } = renderHook(() => useSetup());
|
||||
|
||||
expect(result.current.isPending).toBe(false);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
|
||||
it('returns setup response on success', async () => {
|
||||
const { result } = renderHook(() => useSetup());
|
||||
|
||||
let response: Awaited<ReturnType<typeof result.current.mutateAsync>> | undefined;
|
||||
await act(async () => {
|
||||
response = await result.current.mutateAsync(validSetupData);
|
||||
});
|
||||
|
||||
expect(response?.message).toBe('System initialized');
|
||||
expect(response?.user.role).toBe('Owner');
|
||||
expect(result.current.isPending).toBe(false);
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
|
||||
it('sets error and rethrows when API fails', async () => {
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/Setup/owner`, () =>
|
||||
HttpResponse.json(
|
||||
{ title: 'Conflict', detail: 'Already initialized', status: 409 },
|
||||
{ status: 409 },
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useSetup());
|
||||
|
||||
let thrown: Error | undefined;
|
||||
await act(async () => {
|
||||
try {
|
||||
await result.current.mutateAsync(validSetupData);
|
||||
} catch (err) {
|
||||
thrown = err as Error;
|
||||
}
|
||||
});
|
||||
|
||||
expect(thrown).toBeDefined();
|
||||
expect(result.current.error).not.toBeNull();
|
||||
expect(result.current.isPending).toBe(false);
|
||||
});
|
||||
|
||||
it('resets error state on subsequent successful call', async () => {
|
||||
server.use(
|
||||
http.post(`${API_BASE}/api/v1/Setup/owner`, () =>
|
||||
HttpResponse.json({ title: 'Error', status: 500 }, { status: 500 }),
|
||||
),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() => useSetup());
|
||||
|
||||
await act(async () => {
|
||||
try {
|
||||
await result.current.mutateAsync(validSetupData);
|
||||
} catch {
|
||||
// expected
|
||||
}
|
||||
});
|
||||
|
||||
expect(result.current.error).not.toBeNull();
|
||||
|
||||
// Restore success handler and retry
|
||||
server.resetHandlers();
|
||||
|
||||
await act(async () => {
|
||||
await result.current.mutateAsync(validSetupData);
|
||||
});
|
||||
|
||||
expect(result.current.error).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { api } from '@/lib/api-client';
|
||||
|
||||
interface SetupRequest {
|
||||
name: string;
|
||||
email: string;
|
||||
password: string;
|
||||
language: 'en' | 'nl';
|
||||
}
|
||||
|
||||
interface SetupResponse {
|
||||
message: string;
|
||||
user: {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function useSetup() {
|
||||
const [isPending, setIsPending] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
const mutateAsync = useCallback(async (data: SetupRequest): Promise<SetupResponse> => {
|
||||
setIsPending(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await api.post('/api/v1/Setup/owner', data);
|
||||
return response as SetupResponse;
|
||||
} catch (err) {
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
setError(error);
|
||||
throw error;
|
||||
} finally {
|
||||
setIsPending(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
mutateAsync,
|
||||
isPending,
|
||||
error
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user