diff --git a/frontend/src/features/auth/pages/PasswordReset.test.tsx b/frontend/src/features/auth/pages/PasswordReset.test.tsx index 10b297f..da9d862 100644 --- a/frontend/src/features/auth/pages/PasswordReset.test.tsx +++ b/frontend/src/features/auth/pages/PasswordReset.test.tsx @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import { screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { http, HttpResponse } from 'msw'; @@ -125,6 +125,31 @@ describe('ResetPasswordPage', () => { }); }); + it('leaves no redirect timer behind when the page goes away (it would navigate a torn-down router)', async () => { + mockGuest(); + server.use(http.post(`${AUTH}/reset-password`, () => HttpResponse.json({ message: 'ok' }))); + const set = vi.spyOn(globalThis, 'setTimeout'); + const clear = vi.spyOn(globalThis, 'clearTimeout'); + const { unmount } = renderApp('/reset-password?uid=11111111-1111-1111-1111-111111111111&token=abc'); + + await userEvent.type(await screen.findByTestId('reset-password-input', {}, { timeout: 10000 }), 'Brand-New-Pass9!'); + await userEvent.type(screen.getByTestId('reset-confirm-input'), 'Brand-New-Pass9!'); + await userEvent.click(screen.getByTestId('reset-submit')); + await screen.findByTestId('reset-done'); + + // The page schedules its redirect to the login page after 2.5 seconds. + const redirectTimers = set.mock.calls + .map((call, i) => ({ delay: call[1], id: set.mock.results[i].value as unknown })) + .filter((t) => t.delay === 2500); + expect(redirectTimers).toHaveLength(1); + + unmount(); + + expect(clear).toHaveBeenCalledWith(redirectTimers[0].id); + set.mockRestore(); + clear.mockRestore(); + }); + it('shows one generic "invalid or expired" page for a bad, used or expired link', async () => { mockGuest(); server.use( diff --git a/frontend/src/features/auth/pages/ResetPasswordPage.tsx b/frontend/src/features/auth/pages/ResetPasswordPage.tsx index 44deeb3..e874440 100644 --- a/frontend/src/features/auth/pages/ResetPasswordPage.tsx +++ b/frontend/src/features/auth/pages/ResetPasswordPage.tsx @@ -10,6 +10,7 @@ import { Label } from '@/components/ui/label'; import { NetworkError, ProblemDetailsError } from '@/lib/api-client'; import { resetPasswordFormSchema, type ResetPasswordFormData } from '@/features/auth/schemas/auth'; import { useResetPassword } from '@/features/auth/services/usePasswordReset'; +import { useDelayedAction } from '@/lib/useDelayedAction'; type View = 'form' | 'done' | 'invalid'; @@ -19,6 +20,7 @@ export function ResetPasswordPage() { const navigate = useNavigate(); const search = useSearch({ strict: false }) as { uid?: string; token?: string }; const reset = useResetPassword(); + const later = useDelayedAction(); const [serverError, setServerError] = useState(null); const [view, setView] = useState(search.uid && search.token ? 'form' : 'invalid'); @@ -37,7 +39,7 @@ export function ResetPasswordPage() { try { await reset.mutateAsync({ userId: search.uid!, token: search.token!, newPassword: values.password }); setView('done'); - setTimeout(() => void navigate({ to: '/login' }), 2500); + later(() => void navigate({ to: '/login' }), 2500); } catch (err) { if (err instanceof NetworkError) { setServerError(t('errors.network')); diff --git a/frontend/src/features/invitation/pages/InviteCompletePage.tsx b/frontend/src/features/invitation/pages/InviteCompletePage.tsx index 4841c08..08a72bf 100644 --- a/frontend/src/features/invitation/pages/InviteCompletePage.tsx +++ b/frontend/src/features/invitation/pages/InviteCompletePage.tsx @@ -12,6 +12,7 @@ import { FormErrorBanner } from '@/components/ui/FormErrorBanner'; import { FieldError } from '@/components/ui/FieldError'; import { useValidateInvitation, useCompleteInvitation } from '@/features/invitation/services/useInvitation'; import { ProblemDetailsError, NetworkError } from '@/lib/api-client'; +import { useDelayedAction } from '@/lib/useDelayedAction'; interface FormError { message: string; @@ -29,6 +30,7 @@ export function InviteCompletePage() { const token = search.token || null; const validationQuery = useValidateInvitation(token); const completeMutation = useCompleteInvitation(); + const later = useDelayedAction(); // Handle validation query state changes if (!token) { @@ -71,7 +73,7 @@ export function InviteCompletePage() { const { confirmPassword: _, ...fields } = values; await completeMutation.mutateAsync({ token, ...fields }); setLoadingState('success'); - setTimeout(() => { + later(() => { navigate({ to: '/login' }); }, 2000); } catch (err) { diff --git a/frontend/src/features/setup/pages/SetupPage.tsx b/frontend/src/features/setup/pages/SetupPage.tsx index 35b327e..8b9756a 100644 --- a/frontend/src/features/setup/pages/SetupPage.tsx +++ b/frontend/src/features/setup/pages/SetupPage.tsx @@ -13,6 +13,7 @@ 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 { useDelayedAction } from '@/lib/useDelayedAction'; import { _markSystemInitialized, isSetupTokenRequired } from '@/router'; interface FormError { @@ -26,6 +27,7 @@ export function SetupPage() { const [successMessage, setSuccessMessage] = useState(false); const setupMutation = useSetup(); + const later = useDelayedAction(); const tokenRequired = isSetupTokenRequired(); const [setupToken, setSetupToken] = useState(''); const [tokenMissing, setTokenMissing] = useState(false); @@ -60,7 +62,7 @@ export function SetupPage() { await changeLanguage(values.language); _markSystemInitialized(); setSuccessMessage(true); - setTimeout(() => { + later(() => { navigate({ to: '/login' }); }, 2000); } catch (err) { diff --git a/frontend/src/lib/useDelayedAction.test.tsx b/frontend/src/lib/useDelayedAction.test.tsx new file mode 100644 index 0000000..77c90c2 --- /dev/null +++ b/frontend/src/lib/useDelayedAction.test.tsx @@ -0,0 +1,44 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { renderHook } from '@testing-library/react'; +import { useDelayedAction } from '@/lib/useDelayedAction'; + +describe('useDelayedAction', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it('runs the action after the delay', () => { + const action = vi.fn(); + const { result } = renderHook(() => useDelayedAction()); + + result.current(action, 2000); + vi.advanceTimersByTime(1999); + expect(action).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1); + expect(action).toHaveBeenCalledTimes(1); + }); + + it('never runs the action once the component is gone', () => { + const action = vi.fn(); + const { result, unmount } = renderHook(() => useDelayedAction()); + result.current(action, 2000); + + unmount(); + vi.advanceTimersByTime(10_000); + + expect(action).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + }); + + it('a second request replaces the first (only the latest runs)', () => { + const first = vi.fn(); + const second = vi.fn(); + const { result } = renderHook(() => useDelayedAction()); + + result.current(first, 1000); + result.current(second, 1000); + vi.advanceTimersByTime(1000); + + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + }); +}); diff --git a/frontend/src/lib/useDelayedAction.ts b/frontend/src/lib/useDelayedAction.ts new file mode 100644 index 0000000..d1180de --- /dev/null +++ b/frontend/src/lib/useDelayedAction.ts @@ -0,0 +1,27 @@ +import { useCallback, useEffect, useRef } from 'react'; + +/** + * Runs an action after a delay (for example "show the success message, then go to the login page") and + * cancels it when the component goes away. A bare setTimeout keeps running after unmount: it then navigates + * a router that is no longer there, which in the test runner fires after the test environment was torn down + * ("window is not defined", an unhandled rejection that fails the run) and in the browser acts on a page the + * user already left. + */ +export function useDelayedAction() { + const timer = useRef | null>(null); + + useEffect( + () => () => { + if (timer.current !== null) clearTimeout(timer.current); + }, + [], + ); + + return useCallback((action: () => void, delayMs: number) => { + if (timer.current !== null) clearTimeout(timer.current); + timer.current = setTimeout(() => { + timer.current = null; + action(); + }, delayMs); + }, []); +}