Files
erika/lib/form/form-client.test.ts

63 lines
1.7 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import {
buildFormSchema,
parseStoredDraft,
prepareInitialState,
type Question,
} from "./form-client";
const questions: Question[] = [
{
id: "choice",
formId: "form",
type: "radio",
label: "Choice",
imageUrl: null,
displayOrder: 0,
required: true,
options: ["A", "B"],
allowOther: true,
imageAnswerMode: "none",
},
{
id: "tags",
formId: "form",
type: "checkbox",
label: "Tags",
imageUrl: null,
displayOrder: 1,
required: false,
options: ["A", "B"],
allowOther: true,
imageAnswerMode: "none",
},
];
describe("form client domain helpers", () => {
test("maps stored custom answers to the Other control", () => {
const state = prepareInitialState(questions, {
choice: { value: "Custom", imageCdnId: null },
tags: { value: JSON.stringify(["A", "Custom tag"]), imageCdnId: null },
});
expect(state.values.choice).toBe("__OTHER__");
expect(state.values.tags).toEqual(["A", "__OTHER__"]);
expect(state.otherValues).toEqual({ choice: "Custom", tags: "Custom tag" });
});
test("enforces required answers", () => {
const schema = buildFormSchema(questions);
expect(schema.safeParse({ choice: "", tags: [] }).success).toBe(false);
expect(schema.safeParse({ choice: "A", tags: [] }).success).toBe(true);
});
test("parses versioned drafts and rejects malformed JSON", () => {
expect(
parseStoredDraft(
JSON.stringify({ version: 1, answers: { choice: "A" }, otherValues: {} })
).answers.choice
).toBe("A");
expect(() => parseStoredDraft("not-json")).toThrow();
});
});