import { describe, it, expect } from "vitest"; import { formatDate, toDateInputValue } from "./format-date"; import { EMPTY } from "./placeholder"; describe("formatDate", () => { it("returns the canonical EMPTY placeholder for null/undefined/empty", () => { expect(formatDate(null)).toBe(EMPTY); expect(formatDate(undefined)).toBe(EMPTY); expect(formatDate("")).toBe(EMPTY); }); it("parses a bare YYYY-MM-DD as a local-tz date (no UTC off-by-one)", () => { // The whole point of the helper: a stored "2026-05-03" must render as the // 3rd in every timezone, matching a Date built from local year/month/day — // not shift to the 2nd west of UTC the way `new Date("2026-05-03")` would. const expected = new Date(2026, 4, 3).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric", }); expect(formatDate("2026-05-03", "medium")).toBe(expected); }); it("accepts a Date instance", () => { const expected = new Date(2026, 4, 3).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric", }); expect(formatDate(new Date(2026, 4, 3), "medium")).toBe(expected); }); it("defaults to the medium style", () => { expect(formatDate("2026-05-03")).toBe(formatDate("2026-05-03", "medium")); }); it("supports short and long styles", () => { expect(formatDate("2026-05-03", "short")).toBe( new Date(2026, 4, 3).toLocaleDateString(undefined, { month: "numeric", day: "numeric", year: "2-digit", }), ); expect(formatDate("2026-05-03", "long")).toBe( new Date(2026, 4, 3).toLocaleDateString(undefined, { weekday: "long", month: "long", day: "numeric", year: "numeric", }), ); }); it("includes the time for the datetime style", () => { // ISO datetimes keep their time component. Compare against the same // toLocaleString options the helper uses so the assertion stays // locale-agnostic (no reliance on ASCII digits or a fixed format). const iso = "2026-05-03T15:45:00Z"; const expected = new Date(iso).toLocaleString(undefined, { month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "2-digit", }); expect(formatDate(iso, "datetime")).toBe(expected); }); it("returns an unparseable string verbatim", () => { expect(formatDate("not a date")).toBe("not a date"); }); it("returns EMPTY for an invalid Date instance", () => { expect(formatDate(new Date("nonsense"))).toBe(EMPTY); }); }); describe("toDateInputValue", () => { it("returns an empty string for null/undefined/empty", () => { expect(toDateInputValue(null)).toBe(""); expect(toDateInputValue(undefined)).toBe(""); expect(toDateInputValue("")).toBe(""); }); it("passes a bare YYYY-MM-DD through verbatim", () => { expect(toDateInputValue("2026-05-03")).toBe("2026-05-03"); }); it("returns an unparseable value verbatim", () => { expect(toDateInputValue("not a date")).toBe("not a date"); }); });