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:
2026-11-08 23:51:07 +01:00
co-authored by Claude Sonnet 5.5
parent daaadcbdf7
commit 892c548931
6 changed files with 106 additions and 4 deletions
@@ -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);
});
});
+27
View File
@@ -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);
}, []);
}