import { describe, expect, it } from "vitest"; import type { SchemaProp } from "../../lib/types"; import { selectOptions, selectValue } from "./selectOptions"; const NONE = "بدون"; const CHOOSE = "— اختر —"; const videoType: SchemaProp = { type: "string", enum: ["simulation", "motion", "interactive_motion"], enumLabelsAr: { simulation: "محاكاة تفاعلية", motion: "موشن تعليمي", interactive_motion: "موشن تعليمي تفاعلي", }, }; const withDefault: SchemaProp = { type: "string", enum: ["auto", "ar", "en_gb"], default: "auto", }; const optionalEnum: SchemaProp = { type: "string", enum: ["a", "b"] }; const pick = (prop: SchemaProp, required: boolean, current: unknown) => selectOptions(prop, { required, current, noneLabel: NONE, chooseLabel: CHOOSE }); describe("a required field with no default", () => { it("offers a placeholder while nothing is chosen", () => { const rows = pick(videoType, true, undefined); expect(rows[0]).toEqual({ value: "", label: CHOOSE, disabled: true }); expect(rows.map((r) => r.value)).toEqual([ "", "simulation", "motion", "interactive_motion", ]); }); it("shows the placeholder rather than the first choice", () => { // This is the bug. Without a row whose value is "", the browser displays // the first option while the form holds nothing - so choosing that option // fires no change, and the field reports itself as required while looking // filled in. expect(selectValue(videoType, undefined)).toBe(""); expect(pick(videoType, true, undefined)[0].value).toBe(""); }); it("drops the placeholder once something is chosen", () => { const rows = pick(videoType, true, "motion"); expect(rows.map((r) => r.value)).toEqual([ "simulation", "motion", "interactive_motion", ]); expect(selectValue(videoType, "motion")).toBe("motion"); }); it("brings the placeholder back if the value is not one of the choices", () => { expect(pick(videoType, true, "gone")[0].label).toBe(CHOOSE); }); }); describe("the other two shapes are unchanged", () => { it("a field with a default offers only its choices", () => { expect(pick(withDefault, false, undefined).map((r) => r.value)).toEqual([ "auto", "ar", "en_gb", ]); expect(selectValue(withDefault, undefined)).toBe("auto"); }); it("an optional field with no default offers none", () => { const rows = pick(optionalEnum, false, undefined); expect(rows[0]).toEqual({ value: "", label: NONE }); expect(rows[0].disabled).toBeUndefined(); }); }); describe("the labels", () => { it("come from the schema, and fall back to the raw value", () => { const rows = pick(videoType, true, "motion"); expect(rows[0].label).toBe("محاكاة تفاعلية"); expect(pick(optionalEnum, false, "a")[1].label).toBe("a"); }); });