73 lines
2.3 KiB
TypeScript
73 lines
2.3 KiB
TypeScript
import { expect, test } from 'vitest';
|
|
import {
|
|
connectedDirtyForms,
|
|
markPreparationDirty,
|
|
} from '@/lib/preparation-forms';
|
|
|
|
function form(connected = true): HTMLFormElement {
|
|
const attributes = new Map<string, string>();
|
|
return {
|
|
isConnected: connected,
|
|
setAttribute: (key: string, value: string) =>
|
|
attributes.set(key, value),
|
|
getAttribute: (key: string) => attributes.get(key) ?? null,
|
|
} as unknown as HTMLFormElement;
|
|
}
|
|
function root(forms: HTMLFormElement[]): Pick<Document, 'querySelectorAll'> {
|
|
return {
|
|
querySelectorAll: () =>
|
|
forms.filter(
|
|
(node) =>
|
|
node.getAttribute('data-preparation-dirty') === 'true',
|
|
),
|
|
} as unknown as Pick<Document, 'querySelectorAll'>;
|
|
}
|
|
|
|
test('a restored dirty preparation is protected even before any input event or listener registration', () => {
|
|
const restored = form();
|
|
markPreparationDirty(restored, true);
|
|
expect(connectedDirtyForms([], root([restored]))).toEqual([restored]);
|
|
expect(connectedDirtyForms(new Set([restored]), root([restored]))).toEqual([
|
|
restored,
|
|
]);
|
|
});
|
|
|
|
test('cleaned unmounted and explicitly discarded preparations do not leave false guards', () => {
|
|
const cleaned = form();
|
|
const unmounted = form(false);
|
|
const legacy = form();
|
|
markPreparationDirty(cleaned, false);
|
|
markPreparationDirty(unmounted, true);
|
|
expect(
|
|
connectedDirtyForms(
|
|
[cleaned, unmounted, legacy],
|
|
root([cleaned, unmounted]),
|
|
),
|
|
).toEqual([legacy]);
|
|
markPreparationDirty(legacy, false);
|
|
expect(
|
|
connectedDirtyForms(
|
|
[cleaned, unmounted, legacy],
|
|
root([cleaned, unmounted, legacy]),
|
|
),
|
|
).toEqual([]);
|
|
});
|
|
|
|
test('one submitted form does not remove another dirty preparation from the departure check', () => {
|
|
const submitted = form();
|
|
const other = form();
|
|
markPreparationDirty(submitted, true);
|
|
markPreparationDirty(other, true);
|
|
expect(
|
|
connectedDirtyForms([], root([submitted, other])).some(
|
|
(node) => node !== submitted,
|
|
),
|
|
).toBe(true);
|
|
markPreparationDirty(other, false);
|
|
expect(
|
|
connectedDirtyForms([], root([submitted, other])).some(
|
|
(node) => node !== submitted,
|
|
),
|
|
).toBe(false);
|
|
});
|