test: add unit tests for safeFormRequestSubmit utility

- Test requestSubmit method when available
- Test fallback behavior for iOS Safari 15.5
- Test validation failure prevents form submission
- Ensures proper event dispatching with correct properties
This commit is contained in:
Cursor Agent
2026-01-21 02:54:03 +00:00
parent 7f5c93b629
commit 520c337748

View File

@@ -10,6 +10,7 @@ import {
getMimeType,
getShuffledChoicesIds,
getShuffledRowIndices,
safeFormRequestSubmit,
} from "./utils";
// Mock crypto.getRandomValues for deterministic shuffle tests
@@ -327,3 +328,54 @@ describe("findBlockByElementId", () => {
expect(block).toBeUndefined();
});
});
describe("safeFormRequestSubmit", () => {
let mockForm: HTMLFormElement;
beforeEach(() => {
// Create a mock form element
mockForm = document.createElement("form");
});
test("should call requestSubmit when it's supported", () => {
// Mock requestSubmit as a function
const requestSubmitSpy = vi.fn();
mockForm.requestSubmit = requestSubmitSpy;
safeFormRequestSubmit(mockForm);
expect(requestSubmitSpy).toHaveBeenCalled();
});
test("should use fallback when requestSubmit is not supported", () => {
// Remove requestSubmit to simulate iOS Safari 15.5
mockForm.requestSubmit = undefined as unknown as typeof mockForm.requestSubmit;
const reportValiditySpy = vi.spyOn(mockForm, "reportValidity").mockReturnValue(true);
const dispatchEventSpy = vi.spyOn(mockForm, "dispatchEvent");
safeFormRequestSubmit(mockForm);
expect(reportValiditySpy).toHaveBeenCalled();
expect(dispatchEventSpy).toHaveBeenCalled();
// Verify the submit event was dispatched with correct properties
const dispatchedEvent = dispatchEventSpy.mock.calls[0][0];
expect(dispatchedEvent.type).toBe("submit");
expect(dispatchedEvent.bubbles).toBe(true);
expect(dispatchedEvent.cancelable).toBe(true);
});
test("should not dispatch event when reportValidity returns false", () => {
// Remove requestSubmit to simulate iOS Safari 15.5
mockForm.requestSubmit = undefined as unknown as typeof mockForm.requestSubmit;
const reportValiditySpy = vi.spyOn(mockForm, "reportValidity").mockReturnValue(false);
const dispatchEventSpy = vi.spyOn(mockForm, "dispatchEvent");
safeFormRequestSubmit(mockForm);
expect(reportValiditySpy).toHaveBeenCalled();
expect(dispatchEventSpy).not.toHaveBeenCalled();
});
});