import { afterEach, expect, test, vi } from 'vitest'; import { departureUrl, protectDepartures } from '@/lib/unsaved-navigation'; const state = vi.hoisted(() => ({ before: null as ((event: any) => void) | null, visit: vi.fn(), off: vi.fn(), })); vi.mock('@inertiajs/react', () => ({ router: { on: (_name: string, callback: (event: any) => void) => { state.before = callback; return state.off; }, visit: state.visit, }, })); afterEach(() => { vi.unstubAllGlobals(); vi.clearAllMocks(); }); function fixture() { const doc = new EventTarget(); const win = Object.assign(new EventTarget(), { location: { href: 'http://localhost/requisicoes/criar', assign: vi.fn(), }, }); class Link { href = 'http://localhost/fornecedores?search=QA'; target = ''; download = false; closest() { return this; } hasAttribute(name: string) { return name === 'download' && this.download; } } vi.stubGlobal('document', doc); vi.stubGlobal('window', win); vi.stubGlobal('Element', Link); let dirty = true; let proceed: (() => void) | undefined; const prompt = vi.fn((next: () => void) => { proceed = next; }); const cleanup = protectDepartures(() => dirty, prompt); const link = new Link(); const click = (extra: Record = {}) => { const event = new Event('click', { cancelable: true }); Object.defineProperties( event, Object.fromEntries( Object.entries({ target: link, button: 0, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, ...extra, }).map(([key, value]) => [key, { value }]), ), ); doc.dispatchEvent(event); return event; }; return { doc, win, link, prompt, click, cleanup, clean: () => { dirty = false; }, proceed: () => proceed?.(), }; } test('a dirty form blocks departure to suppliers until the user chooses to leave, retaining the exact destination', () => { const f = fixture(); expect(f.click().defaultPrevented).toBe(true); expect(f.win.location.assign).not.toHaveBeenCalled(); expect(f.prompt).toHaveBeenCalledOnce(); f.clean(); f.proceed(); expect(f.win.location.assign).toHaveBeenCalledWith( 'http://localhost/fornecedores?search=QA', ); f.cleanup(); }); test.each([ { ctrlKey: true }, { metaKey: true }, { shiftKey: true }, { altKey: true }, { button: 1 }, ])( 'new-tab and modified clicks do not abandon the current form: %j', (extra) => { const f = fixture(); expect(f.click(extra).defaultPrevented).toBe(false); expect(f.prompt).not.toHaveBeenCalled(); f.cleanup(); }, ); test('downloads, other targets, same-page anchors and clean forms continue normally', () => { const f = fixture(); f.link.download = true; expect(f.click().defaultPrevented).toBe(false); f.link.download = false; f.link.target = '_blank'; expect(f.click().defaultPrevented).toBe(false); f.link.target = ''; f.link.href = `${f.win.location.href}#linhas`; expect(f.click().defaultPrevented).toBe(false); f.link.href = 'http://localhost/stock'; f.clean(); expect(f.click().defaultPrevented).toBe(false); expect(f.prompt).not.toHaveBeenCalled(); f.cleanup(); }); test('programmatic GET navigation is deferred with filters preserved while saving POST is allowed', () => { const f = fixture(); const visit = { method: 'get', url: new URL('http://localhost/relatorios'), data: { status: 'pending' }, preserveScroll: true, }; const preventDefault = vi.fn(); state.before?.({ detail: { visit }, preventDefault }); expect(preventDefault).toHaveBeenCalledOnce(); expect(state.visit).not.toHaveBeenCalled(); f.clean(); f.proceed(); expect(state.visit).toHaveBeenCalledWith(visit.url, visit); f.cleanup(); const g = fixture(); const allowSave = vi.fn(); state.before?.({ detail: { visit: { ...visit, method: 'post' } }, preventDefault: allowSave, }); expect(allowSave).not.toHaveBeenCalled(); expect(g.prompt).not.toHaveBeenCalled(); g.cleanup(); }); test('reload prompts while dirty, and cleanup removes the listeners', () => { const f = fixture(); const reload = new Event('beforeunload', { cancelable: true }); f.win.dispatchEvent(reload); expect(reload.defaultPrevented).toBe(true); f.cleanup(); const next = new Event('beforeunload', { cancelable: true }); f.win.dispatchEvent(next); expect(next.defaultPrevented).toBe(false); expect(state.off).toHaveBeenCalledOnce(); }); test('departure resolution retains filters and ignores fragment-only, external and non-HTTP links', () => { expect( departureUrl('http://localhost/requisicoes?view=mine', '?view=all'), ).toBe('http://localhost/requisicoes?view=all'); expect( departureUrl('http://localhost/requisicoes?view=mine', '#ajuda'), ).toBeNull(); expect( departureUrl( 'http://localhost/requisicoes', 'mailto:qa@example.invalid', ), ).toBeNull(); expect( departureUrl('http://localhost/requisicoes', 'https://example.invalid'), ).toBeNull(); }); test('submitting a GET search does not guard its own values but still protects another edited form', async () => { const f = fixture(); f.cleanup(); class Form {} vi.stubGlobal('HTMLFormElement', Form); const own = new Form(); let anotherDirty = false; const prompt = vi.fn(); const cleanup = protectDepartures( (except) => anotherDirty || except !== own, prompt, ); const submit = new Event('submit'); Object.defineProperty(submit, 'target', { value: own }); f.doc.dispatchEvent(submit); const preventDefault = vi.fn(); const event = { detail: { visit: { method: 'get', url: new URL('http://localhost/compras/pesquisa?q=QA'), }, }, preventDefault, }; state.before?.(event); expect(preventDefault).not.toHaveBeenCalled(); anotherDirty = true; state.before?.(event); expect(preventDefault).toHaveBeenCalledOnce(); expect(prompt).toHaveBeenCalledOnce(); await Promise.resolve(); cleanup(); });