/** * The beforeunload guard is app-wide (R3 final checks): prevented exactly while the report * is unsaved, on any page; App mounts it, the editor no longer registers its own. */ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, render, renderHook, waitFor } from '@testing-library/react' import App from '@/app/App' import { useUnsavedGuard } from '@/app/useUnsavedGuard' import { useReportStore } from '@/state/reportStore' import type { SheetIndex } from '@/services/sheetIndex' import { loadTestSheet, minimalReport } from '../helpers/sheet' let sheet: SheetIndex beforeAll(async () => { sheet = await loadTestSheet() }) beforeEach(() => { sessionStorage.clear() useReportStore.setState({ report: null, archive: null, saveFailed: false }) useReportStore.getState().hydrateImport({ report: minimalReport(sheet), archive: null }, sheet) }) afterEach(() => { cleanup() vi.restoreAllMocks() useReportStore.setState({ report: null, saveFailed: false }) }) const leave = () => { const event = new Event('beforeunload', { cancelable: true }) window.dispatchEvent(event) return event.defaultPrevented } function fillStorage() { vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => { throw new DOMException('full', 'QuotaExceededError') }) act(() => useReportStore.getState().setConclusion('edited after the quota')) expect(useReportStore.getState().saveFailed).toBe(true) } describe('useUnsavedGuard', () => { it('prevents the unload exactly while the report is unsaved', async () => { renderHook(() => useUnsavedGuard()) expect(leave()).toBe(false) fillStorage() await waitFor(() => expect(leave()).toBe(true)) vi.restoreAllMocks() act(() => useReportStore.getState().setConclusion('saved again')) await waitFor(() => expect(leave()).toBe(false)) }) it('leaves the listener off once the hook unmounts', async () => { const { unmount } = renderHook(() => useUnsavedGuard()) fillStorage() await waitFor(() => expect(leave()).toBe(true)) unmount() expect(leave()).toBe(false) }) it('is mounted by App, on a page that is not the editor', async () => { window.history.pushState({}, '', '/') render() expect(leave()).toBe(false) fillStorage() await waitFor(() => expect(leave()).toBe(true)) }) })