Frontend: geen losse redirect-timers meer na het verlaten van een pagina
Oorzaak van de onbehandelde fout 'window is not defined' in de CI: ResetPasswordPage (en dezelfde constructie in InviteCompletePage en SetupPage) startte een setTimeout voor de doorverwijzing naar de loginpagina en liet die doorlopen na het verlaten van de pagina; in de testrunner vuurde hij nadat de testomgeving was opgeruimd en navigeerde een router die er niet meer was. Nieuwe hook useDelayedAction ruimt de timer op bij het verlaten. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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 { screen } from '@testing-library/react';
|
||||||
import userEvent from '@testing-library/user-event';
|
import userEvent from '@testing-library/user-event';
|
||||||
import { http, HttpResponse } from 'msw';
|
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 () => {
|
it('shows one generic "invalid or expired" page for a bad, used or expired link', async () => {
|
||||||
mockGuest();
|
mockGuest();
|
||||||
server.use(
|
server.use(
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { Label } from '@/components/ui/label';
|
|||||||
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
import { NetworkError, ProblemDetailsError } from '@/lib/api-client';
|
||||||
import { resetPasswordFormSchema, type ResetPasswordFormData } from '@/features/auth/schemas/auth';
|
import { resetPasswordFormSchema, type ResetPasswordFormData } from '@/features/auth/schemas/auth';
|
||||||
import { useResetPassword } from '@/features/auth/services/usePasswordReset';
|
import { useResetPassword } from '@/features/auth/services/usePasswordReset';
|
||||||
|
import { useDelayedAction } from '@/lib/useDelayedAction';
|
||||||
|
|
||||||
type View = 'form' | 'done' | 'invalid';
|
type View = 'form' | 'done' | 'invalid';
|
||||||
|
|
||||||
@@ -19,6 +20,7 @@ export function ResetPasswordPage() {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const search = useSearch({ strict: false }) as { uid?: string; token?: string };
|
const search = useSearch({ strict: false }) as { uid?: string; token?: string };
|
||||||
const reset = useResetPassword();
|
const reset = useResetPassword();
|
||||||
|
const later = useDelayedAction();
|
||||||
const [serverError, setServerError] = useState<string | null>(null);
|
const [serverError, setServerError] = useState<string | null>(null);
|
||||||
const [view, setView] = useState<View>(search.uid && search.token ? 'form' : 'invalid');
|
const [view, setView] = useState<View>(search.uid && search.token ? 'form' : 'invalid');
|
||||||
|
|
||||||
@@ -37,7 +39,7 @@ export function ResetPasswordPage() {
|
|||||||
try {
|
try {
|
||||||
await reset.mutateAsync({ userId: search.uid!, token: search.token!, newPassword: values.password });
|
await reset.mutateAsync({ userId: search.uid!, token: search.token!, newPassword: values.password });
|
||||||
setView('done');
|
setView('done');
|
||||||
setTimeout(() => void navigate({ to: '/login' }), 2500);
|
later(() => void navigate({ to: '/login' }), 2500);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof NetworkError) {
|
if (err instanceof NetworkError) {
|
||||||
setServerError(t('errors.network'));
|
setServerError(t('errors.network'));
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { FormErrorBanner } from '@/components/ui/FormErrorBanner';
|
|||||||
import { FieldError } from '@/components/ui/FieldError';
|
import { FieldError } from '@/components/ui/FieldError';
|
||||||
import { useValidateInvitation, useCompleteInvitation } from '@/features/invitation/services/useInvitation';
|
import { useValidateInvitation, useCompleteInvitation } from '@/features/invitation/services/useInvitation';
|
||||||
import { ProblemDetailsError, NetworkError } from '@/lib/api-client';
|
import { ProblemDetailsError, NetworkError } from '@/lib/api-client';
|
||||||
|
import { useDelayedAction } from '@/lib/useDelayedAction';
|
||||||
|
|
||||||
interface FormError {
|
interface FormError {
|
||||||
message: string;
|
message: string;
|
||||||
@@ -29,6 +30,7 @@ export function InviteCompletePage() {
|
|||||||
const token = search.token || null;
|
const token = search.token || null;
|
||||||
const validationQuery = useValidateInvitation(token);
|
const validationQuery = useValidateInvitation(token);
|
||||||
const completeMutation = useCompleteInvitation();
|
const completeMutation = useCompleteInvitation();
|
||||||
|
const later = useDelayedAction();
|
||||||
|
|
||||||
// Handle validation query state changes
|
// Handle validation query state changes
|
||||||
if (!token) {
|
if (!token) {
|
||||||
@@ -71,7 +73,7 @@ export function InviteCompletePage() {
|
|||||||
const { confirmPassword: _, ...fields } = values;
|
const { confirmPassword: _, ...fields } = values;
|
||||||
await completeMutation.mutateAsync({ token, ...fields });
|
await completeMutation.mutateAsync({ token, ...fields });
|
||||||
setLoadingState('success');
|
setLoadingState('success');
|
||||||
setTimeout(() => {
|
later(() => {
|
||||||
navigate({ to: '/login' });
|
navigate({ to: '/login' });
|
||||||
}, 2000);
|
}, 2000);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { FieldError } from '@/components/ui/FieldError';
|
|||||||
import { useSetup } from '@/features/setup/services/useSetup';
|
import { useSetup } from '@/features/setup/services/useSetup';
|
||||||
import { ProblemDetailsError, NetworkError } from '@/lib/api-client';
|
import { ProblemDetailsError, NetworkError } from '@/lib/api-client';
|
||||||
import { changeLanguage } from '@/i18n/config';
|
import { changeLanguage } from '@/i18n/config';
|
||||||
|
import { useDelayedAction } from '@/lib/useDelayedAction';
|
||||||
import { _markSystemInitialized, isSetupTokenRequired } from '@/router';
|
import { _markSystemInitialized, isSetupTokenRequired } from '@/router';
|
||||||
|
|
||||||
interface FormError {
|
interface FormError {
|
||||||
@@ -26,6 +27,7 @@ export function SetupPage() {
|
|||||||
const [successMessage, setSuccessMessage] = useState(false);
|
const [successMessage, setSuccessMessage] = useState(false);
|
||||||
|
|
||||||
const setupMutation = useSetup();
|
const setupMutation = useSetup();
|
||||||
|
const later = useDelayedAction();
|
||||||
const tokenRequired = isSetupTokenRequired();
|
const tokenRequired = isSetupTokenRequired();
|
||||||
const [setupToken, setSetupToken] = useState('');
|
const [setupToken, setSetupToken] = useState('');
|
||||||
const [tokenMissing, setTokenMissing] = useState(false);
|
const [tokenMissing, setTokenMissing] = useState(false);
|
||||||
@@ -60,7 +62,7 @@ export function SetupPage() {
|
|||||||
await changeLanguage(values.language);
|
await changeLanguage(values.language);
|
||||||
_markSystemInitialized();
|
_markSystemInitialized();
|
||||||
setSuccessMessage(true);
|
setSuccessMessage(true);
|
||||||
setTimeout(() => {
|
later(() => {
|
||||||
navigate({ to: '/login' });
|
navigate({ to: '/login' });
|
||||||
}, 2000);
|
}, 2000);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -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);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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<ReturnType<typeof setTimeout> | 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);
|
||||||
|
}, []);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user