Files
TREK/client/src/utils/globalErrorHandlers.test.ts
T
Maurice 39b6d9f786 feat(client): catch render errors instead of blanking the page (#1805)
* feat(client): catch render errors instead of blanking the page

There were no error boundaries anywhere, so one throw during render unmounted the
whole tree and left the user staring at a white page with no way back.

ErrorBoundary holds the state in a class — getDerivedStateFromError has no hook
equivalent — and renders a function component for the visible half, so the panel
can translate normally. TranslationContext isn't exported, so contextType was not
an option anyway.

Two things it does beyond showing a message. A chunk that 404s after a deploy gets
one reload rather than a retry button: React.lazy caches the rejected promise, so
retrying re-throws immediately. And the reload happens once per session, or a
genuinely missing chunk would spin the tab.

The global handlers in main.tsx cover what no boundary reaches — event handlers
and async code. They filter axios errors: the interceptor already redirects on
401/403 and there are 600+ toast.error call sites, so reporting again would mean
double toasts and, for the redirects, loops.

* feat(client): isolate routes, widgets and the shell chrome

The route boundary goes on the single line where all 16 protected routes render
their content, inside MobileShell rather than around it: the navigation survives,
so a broken page is something the user can walk away from instead of a dead end.
The mobile --m-* tokens live on the shell's .m-root too, so a fallback outside it
would render invisible.

key={location.pathname}, not resetKeys — ProtectedRoute is the same component at
the same position for every protected route, so otherwise a failure could follow
the user across a navigation.

The public routes render outside ProtectedRoute and were therefore uncovered,
including /login (where people land when everything else failed) and the two
anonymous share pages. PublicRoute wraps those seven.

The five global widgets and the shell chrome get fallback={null} each: a broken
widget should disappear quietly, and if BottomNav dies the user loses the very
thing they need to leave the route.

* feat(client): isolate the GL maps and the plugin frame

Both map wrappers put the boundary outside their Suspense, not inside: Suspense
handles a pending promise, a rejected one throws straight past it. Falling back to
the Leaflet renderer keeps a usable map rather than showing an error card — the
same downgrade the Suspense fallback already does while loading.

PluginFrame is third-party code rendering in our tree; a throw there should cost
the plugin, not the page. resetKeys={[pluginId]} so switching plugins clears it.

The locale loader had no .catch (TranslationContext.tsx). After a deploy the chunk
can be gone, which produced an unhandled rejection and left the UI silently on the
previous language. It now keeps the strings it has and says so in the console.
2026-08-06 23:42:57 +02:00

79 lines
3.1 KiB
TypeScript

import { AxiosError } from 'axios';
import { installGlobalErrorHandlers } from './globalErrorHandlers';
let teardown: () => void;
let consoleError: ReturnType<typeof vi.spyOn>;
let reload: ReturnType<typeof vi.fn>;
beforeEach(() => {
sessionStorage.clear();
consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
reload = vi.fn();
Object.defineProperty(window, 'location', { value: { ...window.location, reload }, writable: true });
teardown = installGlobalErrorHandlers();
});
afterEach(() => {
teardown();
consoleError.mockRestore();
});
/** jsdom has no PromiseRejectionEvent, so build the shape the handler reads. */
function rejectWith(reason: unknown) {
const event = new Event('unhandledrejection') as Event & { reason: unknown };
event.reason = reason;
window.dispatchEvent(event);
}
describe('global error handlers', () => {
it('FE-UTIL-GLOBALERR-001: ignores axios rejections, which the app already reports itself', () => {
// The interceptor rejects onward and there are 600+ toast.error call sites;
// logging here as well would turn every handled 500 into a phantom crash.
rejectWith(new AxiosError('Request failed with status code 500'));
expect(consoleError).not.toHaveBeenCalled();
});
it('FE-UTIL-GLOBALERR-002: logs a genuine unhandled rejection', () => {
const reason = new Error('nobody caught me');
rejectWith(reason);
expect(consoleError).toHaveBeenCalledWith('[unhandledrejection]', reason);
});
it('FE-UTIL-GLOBALERR-003: reloads when a dynamic import rejects outside render', () => {
// A lazy chunk can also be pulled in from an effect or a prefetch, where no
// boundary is watching.
rejectWith(new Error('Failed to fetch dynamically imported module: /assets/x-1.js'));
expect(reload).toHaveBeenCalledTimes(1);
expect(consoleError).not.toHaveBeenCalled();
});
it('FE-UTIL-GLOBALERR-004: logs an uncaught error from an event handler', () => {
const error = new Error('thrown in onClick');
window.dispatchEvent(new ErrorEvent('error', { error, message: error.message }));
expect(consoleError).toHaveBeenCalledWith('[window.onerror]', error);
});
it('FE-UTIL-GLOBALERR-005: heals a chunk error arriving as a window error event', () => {
window.dispatchEvent(
new ErrorEvent('error', { error: new Error('Unable to preload CSS for /assets/x.css') }),
);
expect(reload).toHaveBeenCalledTimes(1);
});
it('FE-UTIL-GLOBALERR-006: teardown unsubscribes both listeners', () => {
// Asserted through removeEventListener rather than by firing an event: an
// ErrorEvent with nobody listening is an uncaught error, and vitest reports
// that against the file even when every test passed.
const remove = vi.spyOn(window, 'removeEventListener');
teardown();
expect(remove).toHaveBeenCalledWith('unhandledrejection', expect.any(Function));
expect(remove).toHaveBeenCalledWith('error', expect.any(Function));
// The rejection path has no such side effect, so it is safe to prove silence.
rejectWith(new Error('after teardown'));
expect(consoleError).not.toHaveBeenCalled();
teardown = () => {};
});
});